HashSet Class in Collection Framework

java.util.HashSet;
public class HashSet extends AbstractSet implements Set, Cloneable, java.io.Serializable
HashSet class provides the implementation of Set interface through AbstractSet class. Hash set uses Hash table and it is an unordered, unsorted set.
HashSet class features:
  1. It is an unordered, unsorted set.
  2. It can not contain duplicate elements.
  3. It is unsynchronized.
  4. A HashSet can contain at most one null value.
  5. hashCode() and equals() methods is used for its elements .
  6. Data structure is based on Hash table.
To prevent unsynchronized access to the list:
Set set = Collections.synchronizedSet(new HashSet(…));
Constructor of HashSet
  1. public HashSet()
    It is used to create  an empty set with an initial capacity of 16 and load factor 0.75.
  2. public HashSet(Collection c)
              it is used to create a set containing the elements of the specified collection
  3. public HashSet(int initialCapacity)
             it is used to create an empty set with the specified initial capacity.
  4. public HashSet(int initialCapacity, float loadFactor)
Example of HashSet class
					 
import java.util.Set; import java.util.HashSet; import java.util.Iterator; public class SetDemo { public static void main(String ar[]) { // Create a set Set set= new HashSet(); //Adding elements to the set set.add("Core java"); set.add("Struts"); set.add("Spring"); set.add("j2ee"); set.add("EJB"); set.add("Hibernate"); set.add("Core java"); // Find the size of set System.out.println("There are "+set.size()+" element in the set"); System.out.println("contents of set are......."); // Display set element using iterator method Iterator itr= set.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } System.out.println("Removing EJB from the set....."); set.remove("EJB"); System.out.println("No. of elements after removal :"+ set.size()); System.out.println("Searching struts in the set ........"); System.out.println("Searching element is :" + set.contains("Struts")); } }
Output

There are 6 element in the set
contents of set are.......
EJB
j2ee
Hibernate
Struts
Spring
Core java
Removing EJB from the set.....
No. of elements after removal :5
Searching struts in the set ........
Searching element is :true

Download this example
 



 

Latest Tutorial


Most Visited Tutorial