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

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
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

Joined: Oct 14, 2005
Posts: 19322

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

Joined: Oct 27, 2005
Posts: 19899

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

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.

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

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

Closing thread.

Don't post twice.
jQuery in Action, 2nd edition
subject: Confused with Set equality