The HashSet classes provides four constructors .The first
three constructors crate empty sets of varying sizes:
public HashSet ()
public HashSet (int initialCapacity)
public HashSet (int initialCapacity, int loadFactor)
If initialCapacity is not specified, then initial set size
for storing elements will be the default size of a HashMap, which is either 11
or 101 depending upon the Java version you are using. When the set capacity
reaches full and a new element is added, the internal structure will double in
size before adding the new element. you can also provide custom load factor in
the constructor.
The fourth constructor acts as a copy constructor ,copying
the elements from ine set into the newly created set:
public HashSet (Collection c)
You cannot provide a custom initial capacity or load factor.
Instead, the internal map will be sized at twice the size of collection, or
eleven if the collection is small(five or less elements),keeping the default
load factor of 75%.
Note: If the
original collection had duplicates ,only one of the duplicates will be in the
final created set.
An easy way to initialize a set without manually adding each
element is to create an array of the elements, create a List from that array
with Arrays.asList(), then call this constructor with the list as the
collection:
String st[]={“a”,”b”,”c”,”d”,”e”};
Set set =new HashSet(Arrays.asList(str));
Happy Learning J
No comments:
Post a Comment