Java Generics - Set


Advertisements


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.

Live Demo
package com.tutorialspoint;

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

public class GenericsTester {
   public 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\n", data);
      }

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

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

This will produce the following result −

Output

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


Advertisements