java:Map借口及其子类HashMap四
使用非系统对象作为key,使用匿名对象获取数据
在Map中可以使用匿名对象找到一个key对应的value.
person:
public class HaspMapPerson {
private String name;
private int age;
public HaspMapPerson(String name, int age)
{
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;
}
@Override
public String toString() {
return "姓名:" + name + ", 年龄:" + age ;
}
}
main:
Map<String, HaspMapPerson> allSet = new HashMap<String, HaspMapPerson>();
allSet.put("zhangsan", new HaspMapPerson("zhangsan",30));
allSet.put("lisi", new HaspMapPerson("lisi",33));
//获取value值
System.out.println( allSet.get(new String("zhangsan")) );
结果:姓名:zhangsan, 年龄:30
另外一种情况:
key:是对象, value是string
则无法通过key找到value,为什么之前的string可以?这里需要实现equals()和hashCode来区分是否是同一个对象。
//通过key找到value
Map<HaspMapPerson, String> map = new HashMap<HaspMapPerson, String>();
map.put(new HaspMapPerson("zhangsan",30), "zhangsan");
map.put(new HaspMapPerson("lisi",33), "lis");
System.out.println( map.get(new HaspMapPerson("zhangsan",30)) );
结果为:null
需要修改Person中的 equals()和hashCode()方法:
增加:
public int hashCode()
{
return this.name.hashCode() * this.age;
}
public boolean equals(Object o)
{
if(this == o)
{
return true;
}
if( !(o instanceof HaspMapPerson) )
{
return false;
}
HaspMapPerson p = (HaspMapPerson) o;
if( this.name.equals(p.getName()) && this.age == p.getAge() )
{
return true;
}else {
return false;
}
}
Person:
public class HaspMapPerson {
private String name;
private int age;
public HaspMapPerson(String name, int age)
{
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;
}
@Override
public String toString() {
return "姓名:" + name + ", 年龄:" + age ;
}
public int hashCode()
{
return this.name.hashCode() * this.age;
}
public boolean equals(Object o)
{
if(this == o)
{
return true;
}
if( !(o instanceof HaspMapPerson) )
{
return false;
}
HaspMapPerson p = (HaspMapPerson) o;
if( this.name.equals(p.getName()) && this.age == p.getAge() )
{
return true;
}else {
return false;
}
}
}
执行结果:
zhangsan