- Comparison
- Details
HashSet
Implements Set -> Collection
Duplicates not allowed (returns false, if duplicate is added, no compile time or runtime error)
Insertion order NOT preserved, null insertion allowed, heterogeneous objects allowed
To be used when frequent operation is search
Constructors (Common for all Hash implemented collections)
Default (with initialCapacity as 16 and fillRatio: 0.75 i.e. new HashSet will be created when existing one is filled 75%)
int initialCapacity = Creates with predefined size = initialCapacity and fillRatio = 0.75
int initialCapacity, float fillRatio = Creates with predefined initialCapacity & fillRatio
Collections C = convert any collection to HashSet
LinkedHashSet
Extends HashSet which Implements Set -> Collection
Based on Hashtable + LinkedList
LinkedHashSet is same HashSet except one difference that in LinkedHashSet insertion order is preserved
Best choice to develop cache based applications
TreeSet
Duplicates are not allowed
Null allowed only in empty TreeSet as first element, for rest NullPointerException due to comparison i.e. null.equals()
Insertion order NOT preserved, but elements are inserted according to sorting order
Heterogeneous objects are not allowed (if tried, runtime exception ‘ClassCastException’)
Methods from SortedSet:
first(): first element in the set
last(): last element in the set
headSet(ele): elements less than or equal to ‘ele’
tailSet(ele): greater than or equal to ‘ele’,
subSet(ele1, ele2): >= ele1 and <= ele2
comparator(): returns null, if natural order is used
Constructors
Default (default natural sorting order)
Comparator C: Customized sorting order defined by comparator object
Collections C = convert any collection to TreeSet
SortedSet S = convert SortedSet collection to TreeSet
If TreeSet is defined for an object for which natural sorting is not available i.e. any objects other than numbers & strings, we MUST use Comparator constructor, else we will get ClassCastException
No comments:
Post a Comment