The Set
Interface
A Set is a Collection that cannot contain
duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are not added. The Java Platform contain three general purpose implementations of Set
·       
HashSet 
·       
TreeSet
·       
LinkedHashSet
TreeSet stores its elements in a tree structure, and the elements are orders based on their values. Its performance is slower than
HashSet. LinkedHashSet is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the Set.
Set
Interface Basic Operations
·       
The 
add() method adds the
specified element to the Set if it is not already present. 
·       
The 
remove() method removes the
specified element from the Set if it is present. 
·       
The 
size() operation returns the
number of elements in the Set. The isEmpty() method
is used to check if this set contains no elements
·       
The 
iterator() method returns an Iterator over the Set.
Set
Interface Bulk Operations
Bulk operations are particularly well suited to Sets; when applied, they perform standard set-algebraic
operations. Suppose s1 and s2 are sets. Here's what bulk operations do:s1.containsAll(s2)— returnstrueifs2is a subset ofs1.s1.addAll(s2)— transformss1into the union ofs1ands2.s1.retainAll(s2)— transformss1into the intersection ofs1ands2.s1.removeAll(s2)— transformss1into the set difference ofs1ands2.
Example of Set using HashSet and SortedSet
| 
   
import java.util.*; 
public class SetDemo { 
  public static void main(String args[]) {  
      int numbers[] = {34,
  22,10,60,30,22}; 
      Set<Integer> set = new
  HashSet<Integer>(); 
      try { 
         for(int i = 0; i < 5; i++) { 
            set.add(numbers[i]); 
         } 
         System.out.println("Natural
  Set : "); 
         System.out.println(set); 
         TreeSet sortedSet = new
  TreeSet<Integer>(set); 
         System.out.println("Sorted
  Set : "); 
         System.out.println(sortedSet); 
      } 
      catch(Exception e) {} 
   } 
} 
 |