Set:
Set does not contain any special method except Collection interface methods.
SortedSet:
SortedSet extends Set. The following are the methods which are specially available in SortedSet interface.
public Object first (); public Object last (); public SortedSet headSet (Object obj); xi <= obj public SortedSet tailSet (Object obj1, Object obj2);
java.util.Set:
java.util.SortedSet:
HashSet and TreeSet:
HashSet | TreeSet |
---|---|
1. It extends AbstractSet. | 1. It extends AbstractSet and implements SortedSet. |
2. It follows hashing mechanism to organize its data. | 2. It follows binary trees (AVL trees) to organize the data. |
3. We cannot determine in which order it displays its data. | 3. It always displays the data in sorted order. |
4. Retrieval time is more. | 4. Retrieval time is less. |
5. The operations like insertion, deletion and modifications takes more amount of time. | 5. The operations like insertion, deletion and modifications take very less time. |
6. Creating HashSet is nothing but creating an object of HashSet () class. | 6. Creating TreeSet is nothing but creating an object of TreeSet () class. |
Write a JAVA program which illustrates the concept of TreeSet?
Answer:
import java.util.*; class tshs { public static void main(String[] args) { TreeSet ts = new TreeSet(); System.out.println("CONTENTS OF ts = " + ts); System.out.println("SIZE OF ts = " + ts.size()); ts.add(new Integer(17)); ts.add(new Integer(188)); ts.add(new Integer(-17)); ts.add(new Integer(20)); ts.add(new Integer(200)); ts.add(new Integer(177)); System.out.println("CONTENTS OF ts = " + ts); System.out.println("SIZE OF ts = " + ts.size()); Iterator itr = ts.iterator(); while (itr.hasNext()) { Object obj = itr.next(); System.out.println(obj); } } };
Write a JAVA program which illustrates the concept of HashSet?
Answer:
import java.util.*; class hsts { public static void main(String[] args) { HashSet hs = new HashSet(); System.out.println("CONTENTS OF hs = " + hs); System.out.println("SIZE OF hs = " + hs.size()); hs.add(new Integer(17)); hs.add(new Integer(188)); hs.add(new Integer(-17)); hs.add(new Integer(20)); hs.add(new Integer(200)); hs.add(new Integer(177)); System.out.println("CONTENTS OF hs = " + hs); System.out.println("SIZE OF hs = " + hs.size()); Iterator itr = hs.iterator(); while (itr.hasNext()) { Object obj = itr.next(); System.out.println(obj); } } };