Pages

Hash Set in java

What is Hash Set in java?

Set: child interface of collection.
--> If you want to represent group of individual objects as a single entity, where duplicates are not allowed and insertion order is not preserved then we should go for set.

HashSet (class) ::

--> Duplicate objects are not allowed
--> Insertion order is not preserved and it is based on HashCode
--> null insertion is possible(only once)
--> Hetereogenous objects are allowed
--> Implements serializable and cloneable but not random access interface
--> HashSet is the best choice if our frequent operation is search operation
--> In HashSet duplicates are not allowed if we are trying to insert the duplicates then we won't get any compile or run time errors and add() method simply returns False.

import java.util.HashSet;

public class setDemo {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        System.out.println(hs.add(1));
        System.out.println(hs.add(1));
        System.out.println(hs);
    }
}
Output:
true
false
[1]

Constructors:

1) HashSet h=new HashSet();  //creates an empty hashset object with default initial capacity 16 and default fill ratio: 0.75
2) HashSet h=new HashSet(int initialcapacity); //Created an empty hashset object with specified initial capacity and default fill ratio 0.75
3) HashSet h=new HashSet(int initialcapacity,Float fillratio)
4) HashSet h=new HashSet(Collection c);  //creates an equivalent hashset for given collection.This constructor meant for interconversion between collection objects.
Fill Ratio / Load Factor:: After filling how much ratio a new hashset object will be created,this ratio is called Fill ratio/load factor(0.75)
ex:: Fill ratio 0.75 means, after filling 75% ratio a new hashset object will be created.

Demo Program on HashSet:
import java.util.HashSet;
public class setDemo {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add(1);
        hs.add("1");
        hs.add(null);
        hs.add(3);
        System.out.println(hs.add(3));
        System.out.println(hs);
    }
}
Output:
Hash Set

false
[null, 1, 1, 3]
If we run above program will get mixed output every time you run because insertion order is not preserved in hashset i.e., based on hashcode of the object.
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.