Generic Set in Java

Jakob Jenkov
Last update: 2021-03-10

Java's Set interface (java.util.Set) can be generified. In other words, instances of Set can be given a type, so only instances of that type can be inserted and read from that Set. Here is an example:

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

This set is now targeted at only String instances, meaning only String instances can be put into this set. If you try to put something else into this Set, the compiler will complain.

The generic type checks only exists at compile time. At runtime it is possible to tweak your code so that a String Set has other objects that String's inserted. This is a bad idea, though.


Adding Elements to a Generic Set

Adding elements to a generic Set is done using the add() method, just like you have always done:

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

String string1 = "a string";
set.add(string1);

So what is the big difference? Well, if you try to add an element that is not a String instance, to the Set in the example above, the compiler will complain. That's a pretty nice extra type check to have.


Iterating a Generic Set

You can iterate a generic Set using an iterator, like this:

Set<String> set = new HashSet<String>();
    
Iterator<String> iterator = set.iterator();

while(iterator.hasNext()){
  String aString = iterator.next();
}

Notice how it is not necessary to cast the object returned from the iterator.next() next call. Because the Set is generified (has a type), the compiler knows that it contains String instances. Therefore it is not necessary to cast the objects obtained from it, even if it comes from its Iterator.

You can also use the new for-loop, like this:

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

for(String aString : set) {
    System.out.println(aString);
}

Notice how a String variable is declared inside the parantheses of the for-loop. For each iteration (each element in the Set) this variable contains the current element (current String).

Jakob Jenkov

Featured Videos

Java ForkJoinPool

P2P Networks Introduction




















Advertisements

High-Performance
Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next