Search This Blog

Sunday, 5 March 2017

The Set Interface

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

HashSet stores its elements in a hash table, and performance wise it is the best implementation. It makes no guarantees concerning the order of iteration.

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) — returns true if s2 is a subset of s1.
  • s1.addAll(s2) — transforms s1 into the union of s1 and s2.
  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2.
  • s1.removeAll(s2) — transforms s1 into the set difference of s1 and s2.
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) {}
   }
}

No comments:

Post a Comment