回答!我试图将问题归结为以下代码和输出。简短说明:如果在hashMap中找不到密钥,我们打印出不同的等式概念:==,equals,eq,最后是hashCode和hashMap.contains(key)的重复。它是一个单线程应用程序!
public class EventListAdapter extends BaseAdapter {
protected List<Event> mItems = new ArrayList<>();
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
}
public void setData(List<Event> items){
mItems.clear();
mItems.addAll(items);
notifyDataSetChanged();
}
public void clearData(){
mItems.clear();
notifyDataSetChanged();
}
}
在程序执行期间重复执行代码,产生输出:
val hashMap : collection.immutable.HashMap[State,State] = transition
val key : State = currentState
if (! hashMap.contains(key))
hashMap.keySet.map { entry : State =>
if (entry.ID == key.ID) {
println("================================")
println("entry.ID is " + entry.ID)
println("entry == key is " + (entry == key))
println("entry.equals(key) is " + entry.equals(key))
println("entry eq key is " + entry.eq(key))
println("entry.hashCode == key.hashCode is " + (entry.hashCode == key.hashCode))
println("hashMap.contains(key) is " + hashMap.contains(key))
System.exit(0)
}
}
else
println(s"""Key "${key.ID}" found""")
我不明白这是怎么回事。我甚至可以证明hashMap.keySet包含hashMap中没有包含的元素,我认为这些元素不一致。请注意,'key'是扩展ArrayBuffer的对象(不是类)的实例,其'equals'函数已被覆盖以在ID上进行比较。但是,据我所知,这应该不重要,因为等于功能很重要。非常感谢帮助。
编辑:状态和开始的定义:
Key "Start" found
Key "Start" found
Key "Start" found
================================
entry.ID is Start
entry == key is true
entry.equals(key) is true
entry eq key is true
entry.hashCode == key.hashCode is true
hashMap.contains(key) is false
答案 0 :(得分:2)
我认为你也需要覆盖哈希码。请参阅答案:
Why do I need to override the equals and hashCode methods in Java?