我今天面试了,得到的Java代码如下:
public class Question_6 {
public static void main(String[] args){
Map<Integer,String> map1 = new HashMap<Integer,String>();
map1.put(new Integer(1),"001a");
map1.put(new Integer(1),"001b");
map1.put(new Integer(2),"002");
System.out.println(map1.size());
Map<MyInt,String> map2 = new HashMap<MyInt,String>();
map2.put(new MyInt(1),"001a");
map2.put(new MyInt(1),"001b");
map2.put(new MyInt(2),"002");
System.out.println(map2.size());
}
}
public class MyInt {
int i;
public MyInt(int i) {
this.i = i;
}
}
问题是:
控制台将打印什么?
提出问题的解决方案。
我现在知道第一个问题的答案是:
2
3
但我不知道为什么? MyInt
有什么问题?
最佳答案
您的问题是 equals()
和 hashcode()
未在 MyInt
上实现。
在这两种情况下,您预计都会得到 2
结果。
HashMap
,顾名思义,根据键的hashcode()将键分组到桶中。但对于具有相同值的两个 MyInt
实例,默认哈希码不匹配。
要确定相等性,您还必须重写equals()
。
一种解决方案:
public class MyInt {
[...]
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MyInt) {
return i == ((MyInt)obj).i;
}
return false;
}
}
关于java - Java 中的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819368/