English 中文(简体)
Java Generics - Generic Set
  • 时间:2024-12-22

Java Generics - Set


Previous Page Next Page  

Java has provided generic support in Set interface.

Syntax

Set<T> set = new HashSet<T>();

Where

    set − object of Set Interface.

    T − The generic type parameter passed during set declaration.

Description

The T is a type parameter passed to the generic interface Set and its implemenation class HashSet.

Example

Create the following java program using any editor of your choice.

package com.tutorialspoint;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

pubpc class GenericsTester {
   pubpc static void main(String[] args) {

      Set<Integer> integerSet = new HashSet<Integer>();
  
      integerSet.add(Integer.valueOf(10));
      integerSet.add(Integer.valueOf(11));

      Set<String> stringSet = new HashSet<String>();
  
      stringSet.add("Hello World");
      stringSet.add("Hi World");
 

      for(Integer data: integerSet) {
         System.out.printf("Integer Value :%d
", data);
      }

      Iterator<String> stringIterator = stringSet.iterator();

      while(stringIterator.hasNext()) {
         System.out.printf("String Value :%s
", stringIterator.next());
      }
   }  
}

This will produce the following result −

Output

Integer Value :10
Integer Value :11
String Value :Hello World
String Value :Hi World
Advertisements