hi all,

As of my understanding hash set will not allow duplicates. But when I add two different object of same class with same value it is accepting, at the same time same object with different values are not accepting.Kindly clarify me

Senario-1

        TestBean testBean = new TestBean();
        testBean.setId(1);
        testBean.setId(100);
        HashSet<TestBean> hashSet = new HashSet<TestBean>();
        hashSet.add(testBean);
        testBean = new TestBean();
        testBean.setId(1);
        testBean.setId(100);
        hashSet.add(testBean);
        System.out.println(hashSet.size());

Senario-2

        TestBean testBean = new TestBean();
        testBean.setId(25);
        testBean.setId(100);
        HashSet<TestBean> hashSet = new HashSet<TestBean>();
        hashSet.add(testBean);
        testBean.setId(1);
        testBean.setId(100);
        hashSet.add(testBean);
        System.out.println(hashSet.size());

Edited 2 Years Ago by happygeek: moved

Hi I have mistakenly posted the question in software development insted of java column can any one help me how can I move this to java.

Edited 2 Years Ago by anand01: edit

your assumption is wrong.
First case you have 2 different object instances, that just happen to represent the same data. No problem, both are added.
Second case you have single object instance, that has its data changed. No problem, it's just updated to reflect that data change.

IOW the set works as expected.

APU doc says

public boolean add(E e)

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

So it depends on how equals is implemented for your TestBean class. If you just inherit it from Object then every instance will test as not equal.

This article has been dead for over six months. Start a new discussion instead.