Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
    Bookmark Topic Watch Topic
  • New Topic

Confused with Set equality

 
Venkata Saraswathi
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Report post to moderator
import java.util.*;
class CollTest1
{

public static void main(String[] args)
{
SetElem k1 = new SetElem(1);
SetElem k2 = new SetElem(1);
Set s = new HashSet();
System.out.println(k1.equals(k2)); // #1 true
System.out.println(s.add(k1)); // #2 true
System.out.println(s.add(k2)); // #3 true
System.out.println(s.add(new String("raju"))); //true
System.out.println(s.add(new String("raju"))); //false
System.out.println(s.size());
}
}
class SetElem
{
int i;
public SetElem(int i){
this.i = i;
}
public boolean equals(Object o){
return true;
// return ((SetElem)o).i == this.i;
}
public int hasCode(){
return 1;
// return i;
}
};

How #3 line return true in above example?
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Report post to moderator
Those two objects may be equal, but they don't have the same hash code.

You may think you wrote a method which makes them have the same hash code, but you didn't. Look carefully at it.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
Ooh, that's a tricky one. One that the @Override annotation could have found immediately.
 
W. Joe Smith
Ranch Hand
Posts: 710
  • Mark post as helpful
  • send pies
  • Report post to moderator
It should be noted this same question is posted in the SCJP forum.
 
Campbell Ritchie
Sheriff
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Report post to moderator
Thank you for noticing, W Joe Smith. Here it is.

Closing thread.

Don't post twice.
 
    Bookmark Topic Watch Topic
  • New Topic