Comparison on HashSet, TreeSet, LinkedhashSet :
HashSet | TreeSet | LinkedHashSet |
No Duplicate elements allowed in Set | No Duplicate elements allowed in Set | No Duplicate elements allowed in Set |
Orders cannot be predicted, in can print the data in any order | TreeSet will follow the natural ordering, All elements in the TreeSet should be in same type | LinkedHashSet insertion order will be maintained, Adding duplicate data will not affect the existing order. |
Supports 1 null elements | Supports 1 null elements | Supports 1 null elements |
Gives good performance on read and write | Slow when compared with HashSet, use this only when you need ordering by default | Slow when compared with HashSet, but faster than TreeSet, Use this if you need to maintain the insertion order of the data. |
Example:
package com.candidjava.core; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.TreeSet; public class SetComparison { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("hai"); al.add("12376"); al.add("mathan"); al.add("lal"); al.add("mathan"); al.add("lal"); al.add("ramya"); al.add("suji"); al.add("ravathi"); al.add("sri"); HashSet<String> hs=new HashSet<String>(); hs.addAll(al); TreeSet<String> ts=new TreeSet<String>(); ts.addAll(al); LinkedHashSet<String> lhs=new LinkedHashSet<String>(); lhs.addAll(al); System.out.println("Hash Set ... "+hs); System.out.println("Tree Set ... "+ts); System.out.println("Linked Hash Set ... "+lhs); } }
Output:
Hash Set ... [hai, ramya, ravathi, lal, suji, mathan, 12376, sri] Tree Set ... [12376, hai, lal, mathan, ramya, ravathi, sri, suji] Linked Hash Set ... [hai, 12376, mathan, lal, ramya, suji, ravathi, sri]