我已经定义了一个名为SetOb一个简单的私有类,它包含一个INT和设置数据结构。我在'main'方法中有一个HashMap,其中SetOb为Key和Integer作为值。现在您可以在主要方法中看到,当我使用SetOb实例提供HashMap,然后查找具有完全相同值的实例时,它将返回'null'。在我使用我自己定义的数据结构(如SetOb)作为HashMap中的键时,这种情况在我之前发生过很多次。有人能告诉我我错过了什么吗? 请注意,在SetOb类的构造函数中,我将Set passed as参数复制。的HashMap java中无法散列的MyObject
public class Solution {
public static Solution sample = new Solution();
private class SetOb {
public int last;
public Set<Integer> st;
public SetOb(int l , Set<Integer> si){
last = l;
st = new HashSet<Integer>(si);
}
}
public static void main(String[] args) {
Map<SetOb, Integer> m = new HashMap< SetOb, Integer>();
Set<Integer> a = new HashSet<Integer>();
for(int i =0; i<10; i++){
a.add(i);
}
SetOb x = sample.new SetOb(100, a);
SetOb y = sample.new SetOb(100, a);
m.put(x,500);
Integer val = m.get(y);
if(val!= null) System.out.println("Success: " + val);
else System.out.println("Failure");
}
}
感谢Yogendra,它的工作就像一个魅力:) –