当'key'是两个整数时,如何输出Java HashMap键?
package point;
//an array arr is populated with random x,y points using MyPoint then
public static void main(String[] args) throws IOException {
HashMap<MyPoint,Integer> map = new HashMap<MyPoint,Integer>();
Integer val =0;
for(int i = 0; i < arr.length ; i++)
{
map.put(arr[i],val);
}
}
//second file.
package point;
public class MyPoint implements Comparable<MyPoint>{
private int x;
private int y;
public MyPoint(int x1, int y1) {
x = x1;
y = y1;
}
public boolean equals(Object p) {
MyPoint p1;
try {p1 = (MyPoint) p;}
catch (ClassCastException ex) {return false;}
return (x == p1.x) && (y == p1.y);
}
public int hashCode() {
return ((y * 31) ^ x);
}
这是我的代码MyPoint存储x y点。我使用这段代码来获得唯一的x,y点集,没有重复
我的问题是如何在MyPoint中检索x y值?这是使用HashMap过滤唯一X、Y点的有效方法吗。这里还有我制作的哈希代码
是否有更好的哈希代码可以使用
# 1 楼答案
一个简单的方法是为x和y创建getter方法:
对于HashMap,您可以让它从X坐标映射到具有该X坐标和唯一Y坐标的MyPoints列表(HashMap)。但是,如果您只需要寻找唯一性,那么您可以将每个MyPoint存储在set/ArrayList中,并使用您的。equals()方法。希望有帮助