1 key类覆写equals hashCode 方法
package collectionTest;
import java.util.HashMap;
import java.util.Map;
class Person{
private String name ;
private int age ;
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String toString(){
return "姓名:" + this.name + ";年龄:" + this.age ;
}
@Override
public boolean equals(Object obj) {
if (this == obj){
return true;
}
if (!(obj instanceof Person)){
return false;
}
Person that = (Person)obj;
if (this.name.equals(that.name) && this.age == that.age){
return true;
}
return false;
}
@Override
public int hashCode() {
return this.name.hashCode() * this.age;
}
};
public class MapKeyTest {
public static void main(String[] args) {
Map<Person,String> map = new HashMap<Person,String>() ;
map.put(new Person("张三",30),"zhangsan"); // 增加内容
System.out.println(map.get(new Person("张三",30))) ;
}
}