HashSet
HashSet is the direct
subclass of Set interface , HashSet doesn’t allow duplicates element insertion and insertion
order is not preserved.
- Underlined data structure is HashTable.
- HashSet doesn't allow duplicates.
- Insertion order is not preserved.
- Null insertion is allowed.
- Heterogeneous objects are allowed.
- Implements Serializable and clonable interfaces.
Constructor in HashSet
HashSet hs=new
HashSet(); // creates an empty HashSet
HashSet hs=new
HashSet(int initialCapacity);
//Creates and empty HashSet with passed initialCapacity and
default load factor 0.75.
HashSet hs=new
HashSet(Collection c);
//Creates a HashSet representation of Passed collection
object.
HashSet hs=new
HashSet(int initialCapacity, float loadFactor);
//creates an empty HashSet
with given initialCapacity and given loadFactor.
Example:
import java.util.*; class HashSetDemo { public static void main(String[] args) { HashSet hs=new HashSet(); hs.add(10); hs.add(20); hs.add(30); hs.add(10); hs.add("Hello"); hs.add(null); hs.add(new HashSetDemo()); System.out.println(hs); System.out.println(hs.remove(30)); /*removes the passes argument object from the HashSet and returns true, false otherwise.*/ System.out.println("Total number of elements in the HashSet "+hs.size()); hs.clear(); //clear the entire HashSet System.out.println(hs); } }
No comments:
Post a Comment