Student类:
public class Student {
private int s_id;
private String name;
private int age;
private String description;
public int hashCode(){
return name.hashCode()+age*23;
}
public boolean equals(Object obj){
// 同一个对象放两次就直接返回true
if (this == obj)
return true;
// 判断是不是Student类型
if (!(obj instanceof Student))
return false;
Student s = (Student) obj;
// 姓名和年龄都相同视为重复
return this.name.equals(s.name) && this.age == s.age;
}
public Student(){}
public Student(int s_id, String name, int age, String description) {
super();
this.s_id = s_id;
this.name = name;
this.age = age;
this.description = description;
}
@Override
public String toString() {
return "Student [s_id=" + s_id + ", name=" + name + ", age=" + age
+ ", description=" + description + "]";
}
//setter and getter....
}
main函数:
public static void main(String[] args) throws Exception {
Student s1 = new Student(1,"zqh",22,"deszqh");
Student s2 = new Student(2,"gkn",23,"desgkn");
Student s3 = new Student(3,"lbb",24,"deslbb");
Student s4 = new Student(1,"zqh",22,"deszqh");
Map<Student,String> map = new HashMap<>();
map.put(s1, "01");
map.put(s2, "02");
map.put(s3, "03");
map.put(s4, "04");
//第一种遍历方式:效率高,以后一定要用这种方式(entrySet来遍历)
System.out.println("entrySet来遍历:");
Iterator<Map.Entry<Student,String>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<Student,String> entry = it.next();
System.out.print("键:"+ entry.getKey()+" ");
System.out.println("值:"+ entry.getValue());
}
//第二种,效率低,少用(keySet来遍历)
System.out.println("keySet来遍历:");
Iterator<Student> it2 = map.keySet().iterator();//迭代key值
while(it2.hasNext())
{
Student key = it2.next();
System.out.println("键:"+key+" 值: "+map.get(key));
}
}
输出情况:(1)上面代码中,若直接运行,会输出3个,因为判断的是key值(Student的引用或内容),在这里是复写hashCode和equals方法比较的是Student中的内容。
(2)上面代码中,若注释掉hashCode和equals方法,则会输出4个,即按默认的hashCode和equals方法来比较,找不到重复的。
(3)上面代码中,若仅把Student s4 = new Student(1,"zqh",22,"deszqh");改为 Student s4 = new Student(1,"zqh2",22,"deszqh");即仅仅变了名字,输出4个,因为equals方法返回false,不相等,不认为同样的对象。
(4)上面代码中,若把Student s4 = new Student(1,"zqh",22,"deszqh");改为 Student s4 = new Student(1,"zqh2",22,"deszqh");同时注释Student中的hashCode和equals方法,也输出4个。
遍历情况:注意的是HashMap和HashSet遍历相差不大。