public class ObjTest{
private Integer id;
public boolean equals(Object obj) {
if(obj instanceof ObjTest) {
ObjTest ojb = (ObjTest) obj;
if(this.id.intValue() == ojb.id.intValue()) {
return true;
}
}
return false;
}
public int hashCode() {
return id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
public class HashMapTest {
private static Map<ObjTest, Integer> map = new HashMap<ObjTest, Integer>();
private static void init() {
ObjTest obj1 = new ObjTest();
obj1.setId(3);
ObjTest obj2 = new ObjTest();
obj2.setId(2);
ObjTest obj3 = new ObjTest();
obj3.setId(1);
map.put(obj1, 3);
map.put(obj2, 2);
map.put(obj3, 1);
for(Map.Entry<ObjTest, Integer> e : map.entrySet()) {
ObjTest obj = (ObjTest) e.getKey();
System.out.println("key:" + obj.getId());
}
}
public static void main(String[] args) {
init();
}
}
结果:
key:1
key:2
key:3
求解?
你为什么要关心hashmap遍历元素时的顺序呢?
它之所以在这里是升序,完全是因为你改变了hashmap在进行散列是否的逻辑,当你把ObjTest id得值取其他很大的时候,就不一定是升序的了
关于hashmap进行hash的过程可以参考以下文章:
http://www.ibm.com/developerworks/cn/java/j-lo-hash/?ca=dgr-cn-javaeye0912
hashmap本身就是无序的
LinkedHashMap是有序的
还有你这个遍历的方式不好
最后你要弄清楚为什么要重写hashcode啊
hashcode是在hashmap用来散列的,不是用来拿来排序的