我今天接受了采访,得到了以下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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:
什么将打印到控制台?
建议解决问题的方法.
我现在知道第一个问题的答案是:
2
3
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么?有什么问题MyInt?
gab*_*sch 10
你的问题是,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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1933 次 |
| 最近记录: |