HashSet in java
Java HashSet is an collection class which implements Set interface. It is an un-ordered collection means insertion order is not followed of object in which duplicate value are not allowed.
HashSet
class DeclarationJava HashSet is an collection class which implements Set interface. It is an un-ordered collection means insertion order is not followed of object in which duplicate value are not allowed.
public class HashSet
extends AbstractSet
implements Set, Cloneable, java.io.Serializable { …}
Features
of Hashset class
- HashSet stores unique element only. Duplicate element not allowed if we enter then recent one get override by previous one.
- HashSet uses hashing mechanism to store unique element.
- HashSet does not maintain insertion order because element are stored on the basis of hashing technique.
- HashSet allows null value.
- Hashset class is not thread safe, It means it is non synchronized.
- HashSet is best choice when we perform search operation.
Constructor
and Description
HashSet hs = new HashSet();
Constructs
a new, empty set; the backing HashMap instance has default initial
capacity (16) and load factor (0.75).
HashSet hs = new
HashSet<>(int initialCapacity);
Constructs a new,
empty set; the backing HashMap instance has the specified initial
capacity and default load factor (0.75).
HashSet hs = new HashSet(int initialCapacity, float loadFactor)
Constructs a new,
empty set; the backing HashMap instance has the specified initial
capacity and the specified load factor.
HashSet hs = new HashSet(Collection<? extends E> c)
Constructs a new
set containing the elements in the specified collection.
Java HashSet
Example
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo
{
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(345);
hs.add("abc");
hs.add(123);
hs.add("veer");
hs.add(null);
hs.add("veer");
hs.add("aaa");
/* check element
and size */
System.out.println(hs);
System.out.println("Size is: "+hs.size());
System.out.println("--------------------------");
// Iterating each element
Iterator
itr = hs.iterator();
while(itr.hasNext()){
Object obj = itr.next();
System.out.println(obj);
}
}
}
Output
[null, aaa,
abc, 345, 123, veer]
Size is: 6
--------------------------
null
aaa
abc
345
123
veer
From above output we can see duplicate value are not allowed and
Also insertion order is not followed.
0 comments:
Post a Comment