dcsimg
why my equals() doesnot work.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Zhang_Zhang
Posted On:   Wednesday, October 10, 2001 05:41 AM

I want to save the objects of class Position in a HashSet object. the Position class is as the following: class Position { public Position(){ .... } public boolean equals(Object obj){ if (!(obj instanceof Position)) return false; Position tmp = (Position) obj; if ( x == tmp.px && y == tmp.py) return true; else return false; } private int x, y; } and when I ran the following code: Set set = new HashSet(); set.add(new Position(1, 1)); if (set.contains(Position(1, 1)) System.out.println("True"); else System.out.println("False"   More>>

I want to save the objects of class Position in a HashSet object. the Position class is as the following:

			
class Position {
public Position(){
....
}

public boolean equals(Object obj){
if (!(obj instanceof Position))
return false;
Position tmp = (Position) obj;
if ( x == tmp.px && y == tmp.py)
return true;
else
return false;
}
private int x, y;
}


and when I ran the following code:
			

Set set = new HashSet();
set.add(new Position(1, 1));
if (set.contains(Position(1, 1))
System.out.println("True");
else
System.out.println("False");


the output is False!

Can anyone tell me why? How can I make it correct?    <<Less

Re: why my equals() doesnot work.

Posted By:   Steven_Martin  
Posted On:   Wednesday, October 10, 2001 05:50 AM

Don't forget to overload the hashCode part, not just the equals. Two instances that return true on a equal call should return the same hashCode.
About | Sitemap | Contact