aspose file tools*
The moose likes Beginning Java and the fly likes Confused with Set equality Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Confused with Set equality

Venkata Saraswathi
Ranch Hand

Joined: Sep 27, 2008
Posts: 55
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
Bartender

Joined: Oct 14, 2005
Posts: 18127
    
    8

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

Joined: Oct 27, 2005
Posts: 19543
    
  16

Ooh, that's a tricky one. One that the @Override annotation could have found immediately.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
It should be noted this same question is posted in the SCJP forum.


SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36501
    
  16
Thank you for noticing, W Joe Smith. Here it is.

Closing thread.

Don't post twice.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused with Set equality
 
Similar Threads
Confused with Set equality
HashSet