HashMap Student, String
键:Student 包括name和age
要求:如果两个对象的成员变量值都相同,则为同一个对象
值:String
其中只需要在Student基本类中重写equals()方法即可;
快捷键是alt + shift + s 然后选择h.
Student基本类
package itcast02;
public class Student {
//学生姓名
private String name;
//学生年龄
private int age;
//无参构造
public Student(){
super();
}
//带参构造
public Student(String name, int age){
super();
this.name = name;
this.age = age;
}
//getXxx() setXxx()方法
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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
//使用alt + shift + s 然后选择h重写equals()方法
@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;
}
}
HashMapDemo类
package itcast02;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* HashMap<Student, String>
* 键:Student
* 要求:如果两个对象的成员变量值都相同,则为同一个对象
* 值:String
* @author lgt
*
*/
public class HashMapDemo4 {
public static void main(String[] args) {
//创建集合对象
HashMap<Student, String> hm = new HashMap<Student, String>();
//创建学生对象
Student s1 = new Student("周星驰", 58);
Student s2 = new Student("刘德华", 56);
Student s3 = new Student("梁朝伟", 54);
Student s4 = new Student("刘嘉玲", 50);
//出现两个刘德华,而在之后的遍历中没有被覆盖
//所以,应该在Student类中重新hashCode()方法
Student s5 = new Student("刘德华", 56);
Student s6 = new Student("张学友", 61);
//添加元素
hm.put(s1, "111");
hm.put(s2, "222");
hm.put(s3, "333");
hm.put(s4, "444");
hm.put(s5, "555");
hm.put(s6, "666");
//遍历方式1 根据键查找值
//获取所有的键
Set<Student> stu = hm.keySet();
//遍历键的集合,获取每一个键
for(Student s : stu){
//根据键查找值hm.get(s)
System.out.println(s.getName() + "---" + s.getAge() + "---" + hm.get(s));
}
System.out.println("----------------------");
//遍历方式2 根据键值对对象查找键和值
//获取所有的键值对对象的 集合
Set<Map.Entry<Student, String>> st = hm.entrySet();
//遍历键值对对象的集合st,获取每一个键值对对象
for(Map.Entry<Student, String> s : st){
//根据键值对对象获取键和值
Student stemp = s.getKey();
String str = s.getValue();
System.out.println(stemp.getName() + "---" + stemp.getAge() + "---" + str);
}
}
}
本文介绍了一个使用HashMap存储Student对象的应用实例。通过重写Student类的equals()和hashCode()方法,确保了当两个对象的成员变量值相同时被视为同一个对象。
1801

被折叠的 条评论
为什么被折叠?



