• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concept of Set  RSS feed

 
Ayan Dutta
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi , I have a conceptual problem regarding set .
In a set the elements should be unique.When a attempt is made to insert a duplicate element inside a Set ,how the checking is done ? what is compared for the elements ,the HashCode of the objects ?

For example the following code

----------------------------------------------------
package test;

import java.util.Set;
import java.util.HashSet;

public class TestSet
{
private String name ="";
public void setName(String name)
{
this.name = name;
}

public static void main(String[] args)
{
Integer a = new Integer(100);
Integer b = new Integer(100);

Set set1 = new HashSet();
set1.add(a);
set1.add(b);
System.out.println("Set1 :" + set1);

//clear the Set
set1.clear();

TestSet ts1 = new TestSet();
TestSet ts2 = new TestSet();
ts1.setName("A");
ts2.setName("A");

set1.add(ts1);
set1.add(ts2);

System.out.println("Set1 :" + set1);
}
}
-------------------------------------------------------

The out put is
-------------------------------------------------
Set1 :[100]
Set1 :[test.TestSet@82ba41, test.TestSet@10b62c9]
-------------------------------------------------

Now the first two integers are also two different objects .
then why both of them are not added ?

Regards,
Ayan
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TestSet doesn't implement "equals", so despite the identical member variables, the two objects are different as far as Java is concerned. Now, whenever you implement equals() you must also implement hashCode() correctly, or some other classes (and HashSet is definitely one of those) won't work correctly with your class. See the Javadocs for Object.equals() and Object.hashCode() -- the methods that TestSet needs to override --- for a detailed explanation.

Integer works as you'd expect because Integer correctly overrides equals() and hashCode().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!