The Set interface in Java

The interface java.util.set  is a subtype of the interface java.util.Collections . It represents a set of objects, each of which can exist only once. The set interface contains only the methods inherited from Collections.

Implementations of Set

The Java platform has 3 implementations of Set. You can choose one of the following Object Collections:
  • java.util.HashSet
  • java.util.TreeSet
  • java.util.LinkedHashSet
Each of these implementations stores the elements in a hash table. which is the best implementation, but it's different when it comes to the scan of the set and the order of the items, and the access time and changes in those lists. Set instances are comparable despite their differences, two implementations are equal if they contain the same elements.

HashSet is returned by a HashMap. There is no guarantee that the sequence will be followed during the course.

TreeSet order the elements according to the values and not with the keys which is a bit slow than HashTable.

LinkedList order items based on the order during insert.

Here are some examples of how to create the Set:

Set hset = new HashSet(); 
Set tset = new TreeSet();
Set lset = new LinkedHashSet();

Basic Set

1)void add(Object o)
Adds an item to the collection. This method is inherited from the interface Collection.


Set hset = new HashSet(); 
hset.add(new String("1"));
hset.add(new String("2"));
2)boolean remove(Object o)
Removes the specific item from the collection. If it exists, it returns a boolean true.

hset.remove("1"); 
3)Iterator iterator()
Returns an iterator on Set.

Set hset = new HashSet(); 
Iterator iterator = hset.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}
4)Int size()
Returns the number of items in the set Set.

System.out.println(hset.size()); 

Generic declaration of Set

Objects can be added by default in the set Set  but it is possible to limit the type of object you want to insert in Set:

Set< String> set = new HashSet< String> (); 
This statement accepts only String objects. The advantage is that you can then use and directly access Set without cast:

for(String Object : set){
//do something
}
References:
Java Collection: Set
Javadoc: The Set Interface