1 3 5 存map 实现有序存取
Map<Test, Integer> map = new HashMap<>();
Test test1 = new com.myzy.auth.controller.Test();
test1.setCode(1);
Test test2 = new com.myzy.auth.controller.Test();
test2.setCode(2);
Test test3 = new com.myzy.auth.controller.Test();
test3.setCode(3);
map.put(test1, 1);
map.put(test2, 1);
map.put(test3, 1);
Iterator<Map.Entry<Test, Integer>> iterable = map.entrySet().iterator();
while (iterable.hasNext()) {
Map.Entry<Test, Integer> entry = iterable.next();
System.out.println(entry.getKey());
}
public boolean equals(int code) {
return false;
}
public int hashCode() {
return 100;
}
重写equals方法为始终不相等,重写hashcode方法始终为相等
看懂的给个回复!!!!!!!!!!!!
本文探讨了在Java中使用HashMap实现有序存取的问题。通过创建一个Map实例并插入三个Test对象,虽然Map本身不保证顺序,但在迭代时发现由于Test对象的equals始终返回false和hashCode始终返回相同值,导致预期的有序存取无法实现。文章着重分析了equals和hashCode方法在HashMap中的作用,并提醒读者注意这两个方法的正确实现对于Map的行为至关重要。
425

被折叠的 条评论
为什么被折叠?



