Set

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.

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

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;

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

  Set&lt;Integer&gt; integerSet = new HashSet&lt;Integer&gt;();
  integerSet.add(Integer.valueOf(10));
  integerSet.add(Integer.valueOf(11));
  Set&lt;String&gt; stringSet = new HashSet&lt;String&gt;();
  stringSet.add("Hello World");
  stringSet.add("Hi World");
  for(Integer data: integerSet) {
     System.out.printf("Integer Value :%d\n", data);
  }
  Iterator&lt;String&gt; 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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *