Home  >  Core Java

Example of HashSet in Java

By Arvind Rai, June 09, 2013
java.util.HashSet implements Set. In HashSet, no duplicate object can be added. The class which object is being added in Set must implements hashCode and equals to check unique ness of object. HashSet can be iterated with new for loop. Find the example below.
HashSetDemo.java
package com.concretepage.util;
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
    public static void main(String[] args) {
        Set<Bean> set = new HashSet<Bean>();
        Bean b1 = new Bean("A");
        Bean b2 = new Bean("B");
        Bean b3 = new Bean("C");
        set.add(b1);
        set.add(b2);
        set.add(b3);
        for(Bean b : set){
            System.out.print(b.name+" ");
        }
        System.out.println("\nsize before duplicate element:"+set.size());
        //add duplicate in Set
        Bean b4 = new Bean("C");
        set.add(b4);
        //no effect on size
        System.out.println("size after duplicate element:"+set.size());
    }
}
class Bean {
    public String name;
    public Bean(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Bean)o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
}
Output
C A B 
size before duplicate element:3
size after duplicate element:3 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us