这是我的代码:
package AbstractClassesTwo;
class X {
private int n;
public X(int n){
this.n = n;
}
public String toString(){
return "[" + n + " ]";
}
public boolean equals (Object obj){
boolean b = false;
if(obj instanceof X){
X x = (X)obj;
b = this.n == x.n;
}
return b;
}
public int hashCode(){
return n;
}
}
和司机班:
package AbstractClassesTwo;
import java.util.HashMap;
public class UseX {
public static void main (String[] args){
X x1 = new X(1);
X x2 = new X(2);
String s1 = "1 ett one";
String s2 = "2 två two";
HashMap<X, String> t = new HashMap<X, String>();
t.put(x1, s1);
t.put(x1, s2);
int i = (int) (2 * Math.random() + 1);
X n = new X(i);
String s = (String)t.get(n);
System.out.println(n + ": " + s);
}
}
值s在多次执行时返回空值和字符串值(" 2 två two"
)?
答案 0 :(得分:6)
t.put(x1, s1);
t.put(x1, s2);
^^
不应该是x2
吗?每当您查找new X(2)
时,都会获得null
。