现在有这么一个类。
public Chest {
public HashMap<Key, String> map = new HashMap<Key, String>();
public void test(){
map.put(new Key(1, 1), "tt");
System.out.println(map.get(new Key(1, 1));
}
}public Key() {
private int x;
private int y;
public Key(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Key k){
if (x == k.x && y == k.y) {
return true;
}esle {
return false;
}
}
public int hashCode() {
return (x*7 + y*23);
}
}为什么new了Chest的实例之后调用test(),返回的总是null呢?总是认为找不到Key对应的Value?
public Chest {
public HashMap<Key, String> map = new HashMap<Key, String>();
public void test(){
map.put(new Key(1, 1), "tt");
System.out.println(map.get(new Key(1, 1));
}
}public Key() {
private int x;
private int y;
public Key(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Key k){
if (x == k.x && y == k.y) {
return true;
}esle {
return false;
}
}
public int hashCode() {
return (x*7 + y*23);
}
}为什么new了Chest的实例之后调用test(),返回的总是null呢?总是认为找不到Key对应的Value?
建议将test()方法改成如下试试:
public void test()
{
Key key = new Key(1,1);
map.put(key,"tt");
System.out.println(map.get(key);
}
public void test(){
Key key=new Key(1, 1);
map.put(key, "tt");
System.out.println(map.get(key));}这样可以.
@Override
public boolean equals(Object obj) {
if(obj instanceof Key){
Key k =(Key)obj;
if(x==k.x&&y==k.y)
return true;
}
return false;
}
HashMap<Key, String> map = new HashMap<Key, String>();
Key key = new Key(1, 1);
map.put(key, "tt");
System.out.println(map.get(key));//用new是新创建一个对象,是不同的引用
}
}class Key {//这是定义类
private int x;
private int y; public Key(int x, int y) {
this.x = x;
this.y = y;
} public boolean equals(Key k) {
if (x == k.x && y == k.y) {
return true;
} else {
return false;
}
} public int hashCode() {
return (x * 7 + y * 23);
}
}这样就可以了,返回结果:tt
网上应该有介绍的