本帖最后由 黄克帅 于 2012-6-11 13:34 编辑
为什么自己创建的对象,put方法放入Map的时候覆盖不了相同的key。而我直接用Integer 对象 就会覆盖相同key的value
public class Zi {
private String name;
private int age;
public Zi(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Zi, String> hm = new HashMap<Zi, String>();
hm.put(new Zi("aa",1), "a");
hm.put(new Zi("bb",2), "b");
hm.put(new Zi("cc",3), "c");
hm.put(new Zi("aa",1), "d");
Set<Zi> zi = hm.keySet();
Iterator<Zi>it =zi.iterator();
while(it.hasNext()){
Zi str = it.next();
System.out.println(str.getAge()+"---"+str.getName()+"---"+hm.get(str));
//这里打印
//1---aa---a
//3---cc---c
//1---aa---d
//2---bb---b
// put方法不是重复key对应的value的会被覆盖吗,这里为什么没有覆盖
}
HashMap<Integer, String> hm1 = new HashMap<Integer, String>();
hm1.put(1, "a");
hm1.put(2, "b");
hm1.put(3, "c");
hm1.put(1, "d");
Set<Integer> in = hm1.keySet();
Iterator<Integer> ite = in.iterator();
while(ite.hasNext()){
Integer inte =ite.next();
System.out.println(inte+"---"+hm1.get(inte));
//这里打印
//1---d
//2---b
//3---c
//这里重复key对应的value被覆盖了
}
}
} |
|