如何把坐标作为hashmap的key

来源:互联网 发布:广西干部网络培训平台 编辑:程序博客网 时间:2024/06/07 17:17

1. 首先把坐标封装成一个Point类:重写equals 和hashCode 方法,直接上代码。。。

Point类

public class Point {
private int x;
private int y;
private int z;

/*省略set/get 方法;*/

public Point(int x, int y,int z){
this.x=x;
this.y=y;
this.z=z;
}
@Override
public boolean equals(Object obj) {
//这里要谨慎写
if(this==obj) return true;
if(!(obj instanceof Point)) return false;
Point point  = (Point)obj;
return x==point.x && y==point.y && z==point.z;
}
@Override
public int hashCode() {

return x^y*137^z*11731; //尽量用大奇数
}


}

2.测试类 MyHashTest

public class MyHashTest {
public static void main(String[] args) {
HashMap<Point, int []> map =new HashMap<Point,int []>();
int [] a ={3,5,6,2,11};
int [] b = {2,4,6,7};
Point point = new Point(1, 5, 9);
Point point2 = new Point(2, 6, 3);

map.put(point, a);
map.put(point2, b);

int[] mString = map.get(point);
for(int c:mString){
System.out.print(c+"  ");
}
}


}

原创粉丝点击