package org.cc.map;
class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public String toString() {
return this.name+"的年龄是"+this.age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
if (!(obj instanceof Person))
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
复制代码package org.cc.map;
import java.util.HashMap;
import java.util.Map;
public class HashMapdemo {
public static void main(String[] args) {
Map<Person,String> m=null;
m=new HashMap<Person,String>();
Person per=new Person(13,"张三");
m.put(per,"1");
System.out.println(m.get(per));
System.out.println(m.get(new Person(13,"张三")));
per.setAge(14);
System.out.println(m.get(per));
System.out.println(m.get(new Person(13,"张三")));
System.out.println(m.get(new Person(14,"张三")));
}
}
复制代码/*
修改了key之后就找不到value了
1
1
null
null
null
*/
为什么修改Person后 用匿名对象也会找不到...........希望能讲解下 ..是不是和堆内存内per的值被修改了有关?....
|