-
June 27th, 2013, 10:52 AM
#1
Hash Set Question
Hi
I am analysing a particular code and have some questions
Code:
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
import java.util.HashSet;
import java.util.Set;
public class PointMain {
public static void main(String args[]){
System.out.println(onUnitCircle(new Point(1, 0)));
}
// Initialize UnitCircle to contain all Points on the unit circle
private static final Set<Point> unitCircle;
static {
unitCircle = new HashSet<Point>();
unitCircle.add(new Point( 1, 0));
unitCircle.add(new Point( 0, 1));
unitCircle.add(new Point(-1, 0));
unitCircle.add(new Point( 0, -1));
}
public static boolean onUnitCircle(Point p) {
return unitCircle.contains(p);
}
}
I get a false when i do a contains on a hashset. I am thinking that it should yield true.
The question i had was that without overriding the equals or the hashcode when i store the values in a Hash Set and do a contains i am assuming that it might have the equals and hashcode implemented. Would this be correct then- when i am using the hash set to store my objects the right way to use the contains is that i implement a hashcode and a equals method in object that i am going to do the contains on?
Thanks,
Frank
-
July 22nd, 2013, 11:59 AM
#2
Re: Hash Set Question
Originally Posted by frankyfish
without overriding the equals or the hashcode
You must supply equals and hashCode methods in Point. Otherwise it won't work with the standard hash based collections, such as HashSet.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|