question_016-JAVA之Map的
HashMap键为自定义对象
----------------------------------------------------
Map<Student, String>
键为:自定义对象Student 【为保证键唯一,必须重写Student的 hashcode和equals方法】
值为:字符串
----------------------------------------------------
Student的定义如下:
package com.lyMapDemo;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
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;
}
// 为保证自定义对象的唯一性,必须重写HashCode和equals方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) 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 com.lyMapDemo;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo2 {
public static void main(String[] args) {
// 创建对象
Map<Student, String> hm = new HashMap<Student, String>();
// 创建学生对象
Student s1 = new Student("貂蝉", 12);
Student s2 = new Student("王昭君", 13);
Student s3 = new Student("西施", 14);
Student s4 = new Student("杨贵妃", 15);
Student s5 = new Student("貂蝉", 12);
// 加入HashMap
hm.put(s1,"11112");
hm.put(s2,"222223");
hm.put(s3,"333334");
hm.put(s4,"444445");
hm.put(s5,"555556");
// 方式1遍历:键集合
Set<Student> set = hm.keySet();
for(Student i : set){
// 取值
String s = hm.get(i);
System.out.println(i.getName() + "---" + i.getAge() +"---"+ s);
}
}
}
······················结果·······················
貂蝉---12---555556
杨贵妃---15---444445
西施---14---333334
王昭君---13---222223
···········注·····························································
如果不重写hashcode和equals,则得到如下结果······
杨贵妃---15---444445
西施---14---333334
貂蝉---12---555556
貂蝉---12---11112
王昭君---13---222223
·····················································