Google News
logo
Java Hash Sets
Set
A set represents a group of elements arranged just like an array. The set will grow dynamically when the elements are stored into it. A set will not allow duplicate elements. If we try to pass the same element that is already available in the set, then it is not stored into the set. Set has mainly two types of classes. 

They are:
a. HashSet Class
b. LinkedHashSet Class
HashSet Class
1. Introduced in 1.2 v 

2. Duplicate objects are not allowed if we are trying to insert duplicate values then we won't get any compilation errors an wont get any Execution errors simply add method return false. 

3. Null insertion is possible 

4. Heterogeneous objects are allowed 

5. The under laying data structure is hashTable. 

6. Insertion order is not preserved.
Creating HashSet object:
We can create a HashSet objects in many different ways as shown below:
a. HashSet hs = new HashSet< String >(); 
The preceding statement constructs a HashSet which stores String type objects. 

 We can also mention the capacity at the time of creating ArrayList object as: 
b. HashSet hs = new HashSet(100);
The preceding statement constructs a HashSet with a initial capacity declared as 101. This capacity may increase automatically when more number of elements are being stored.
HashSet proram
import java.util.*; 
class Test 
{ 
public static void main(String[] args) 
{ 
HashSet h=new HashSet(); 
h.add("a"); 
h.add("a"); 
h.add("aaaa"); 
h.add(10); 
h.add(null); 
System.out.println(h); 
} 
}
Output :
[null, aaaa, a, 10]