Set
Set Interface also extends the Collection Interface. Set mean that it does not allow duplicate element i.e it care about uniqueness. There are three classes that implements Set interface
- HashSet
- TreeSet
- LinkedHashSet
Difference between HashSet, TreeSet and LinkedHashSet
| HashSet | TreeSet | LinkedHashSet |
|---|---|---|
| A HashSet is unsorted, unordered, no duplicates. | A TreeSet is sorted and no duplicates. | It is an Ordered version of HashSet and no duplicates. |
| Inherit from set. | Inherit from SortedSet | Inherit from set. |
| It is heterogeneous. | It is homogeneous. | It is heterogeneous. |
Syntax of ArrayList, Vector and LinkedList :
| Set | Create | Add | Traverse |
|---|---|---|---|
| HashSet | HashSet name=new HashSet(); | name.add("name1"); name.add("name2"); | Iterator i =name.iterator(); |
| TreeSet | TreeSet name=new TreeSet(5); | name.add("name1"); name.add("name2"); | Iterator i =name.iterator(); |
| LinkedHashSet | LinkedHashSet name=new LinkedHashSet(5); | name.add("name1"); name.add("name2"); | Iterator i =name.iterator(); |
Example to show HashSet insertion :
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashSetDemo {
String name;
String address;
Integer id;
public HashSetDemo(String name, String address,Integer id)
{
this.name=name;
this.address=address;
this.id=id;
}
public String toString()
{
return "name ="+name+" address = "+" id = "+id;
}
public static void main(String[] args) {
HashSetDemo hsd1=new HashSetDemo("Peter","USA",1001);
HashSetDemo hsd2=new HashSetDemo("James","UK",1002);
HashSetDemo hsd3=new HashSetDemo("Tim","Australia",2000);
Set hash=new HashSet();
hash.add(hsd1);
hash.add(hsd2);
hash.add(hsd3);
hash.add(hsd4);
System.out.println(hash);
}
}



