use*_*234 -3 java hash hashcode
我有关于java equals和hashcode的声明.
如果我们将这样的Integer对象用于HashMap中的键,我们将无法可靠地检索关联的值
这是什么意思 ?为什么它说"不可靠"?我写了一个测试程序,它始终有效.
public class Test1 {
public static void main(String[] args){
Map<Integer, Student> map = new HashMap<Integer, Student>();
map.put(1, new Student("john"));
map.put(2, new Student("peter"));
Student s1 = map.get(1);
Student s2 = map.get(1);
Student s3 = map.get(2);
System.out.println("s1:"+s1+" s2:"+s2+" s3:"+s3);
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s2));
}
}
class Student{
private String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 12
你误会了!阅读整段:
如果Integer没有覆盖equals()和hashCode()会发生什么?没有,如果我们从未使用Integer作为HashMap或其他基于散列的集合中的键.但是,如果我们将这样的Integer对象用于HashMap中的键,我们将无法可靠地检索关联值,除非我们在put()调用中使用完全相同的Integer实例,就像我们在put中所做的那样()打电话.
http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html
这就是说Integer该类必须有一个hashCode()方法并且equals()才能工作.它确实有这些方法,所以没关系.它会工作.
示例说,不应比较对存储值的对象的引用,因为Integers具有相同整数值的两个实际上可能是不同的对象.
Integer x = new Integer(5);
Integer y = new Integer(5);
Run Code Online (Sandbox Code Playgroud)
x.equals(y)总是如此.x == y并非总是如此(但有时也可以).规则会针对不同的价值范围而变化.==除非您完全确定自己知道自己在做什么,否则永远不要依赖任何对象引用.
另请注意,您传递的int参数(基本类型)不是Integers(对象的引用),而是您的集合的泛型类型Integer.这意味着还有拳击投入等式!