Set Interface

Set Interface

Set interface extends the collection interface.A set cares about uniquenes--it doesnot allow duplicates.More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.This interface contains only methods inherited from Collection interface.
The three Set implemenations are :
HashSet,
LinkedHashSet
and
TreeSet.

HashSet

HashSet  is an unsorted,unordered Set.It uses the hashCode() of the object being inserted.Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

import java.util.*;
 public class RajniHashSetTest {
            public static void main(String[] args) {
                        boolean[] bSet = new boolean[5];
                        Set<Object> s = new HashSet<Object>();
                        bSet[0]=s.add("x");
                        bSet[1]=s.add(new Integer(12));
                        bSet[2]=s.add("y");
                        bSet[3]=s.add("x");  //will returned false.
                        bSet[4]=s.add(new Object());
                        System.out.println(bSet.length);
                        for(int i=0;i<bSet.length;i++)
                                    System.out.print(bSet[i] + " ");
                        for(Object o : s)
                                    System.out.print("\n"+ o + " ");
            }
 }
Output  :
5
 true true true false true
java.lang.Object@19821f
12
y
x


More methods related to HashSet.

TreeSet

Use TreeSet when you need to extract elements from collection in sorted order.Elements are added in sorted manner.This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements .
            Be carefull while using the TreeSet,the elements added in this ,must be mutually comparable.

import java.util.*;
 public class RajniTreeSet {
            @SuppressWarnings("unchecked")
            public static void main(String[] args) {
                        boolean[] bSet = new boolean[5];
                        Set s = new TreeSet();
                        bSet[0]=s.add("x");
                        bSet[1]=s.add(new Integer(12)); //will ClassCastException
                        bSet[2]=s.add("y");
                        bSet[3]=s.add("x"); 
                        for(int i=0;i<bSet.length;i++)
                                    System.out.print(bSet[i] + " ");
            }
 }

Output:
Exception in thread "main"
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integerat java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at rajni.CandoAnyThing.RajniTreeSet.main(
RajniTreeSet.java:10)

If you try to add the objects of the class, which is not already predefined then you must have to implements the Comparable interface to the class whose objects are being added in TreeSet, else it will throw java.lang.ClassCastException.

public class Rajni implements Comparable<Object>  {
            int i;
            Rajni(int i){
                        this.i=i;
            }
            @Override
            public int compareTo(Object o) {
                        return 0;
            }
 }

After implementing Comparable interface you can add its object to TreeSet.

 import java.util.*;
   public class TreeSetWithComparable {
            public static void main(String[] args) {
                        Rajni r1 = new Rajni(3);
                        Rajni r2 = new Rajni(9);
                        Rajni r3 = new Rajni(5);
                        Set<Rajni> rajniTree = new TreeSet<Rajni>();
                        rajniTree.add(r1);
                        rajniTree.add(r2);
                        rajniTree.add(r3);
                        System.out.println(rajniTree);
        }
   }

More methods related to TreeSet.

mind it !!!
In fact whenever you use sort() method in any collection for the class whose object is being sorted that class must have to implements comparable or comparator interface else will throw ClassCastException.

LinkedHashSet

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.Use this instead of HashSet when you care about the iterartion order.

import java.util.*;
 public class RajniLinkedHashSetTest {
   @SuppressWarnings("unchecked")
 public static void main(String args[]) {
      Set hs = new LinkedHashSet();
      hs.add("A");
      System.out.println(hs.add("A")); 
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}

Output:
false
[A, D, E, C, F]

For more methods related to LinkedHashSet.

You must want to read about ArrayList, Vector, Map Interface

No comments:

Post a Comment