package cn.map;
import java.util.HashMap;
import java.util.Iterator;
/**
* HashMap的数据结构是哈希表
*
* HashMap存储自定义对象演示,
* 学生类:属性有姓名和年龄
* 籍贯类:属性有省份、城市、乡镇
* @author Administrator
*
*/
public class HashMapDemo {
public static void main(String[] args) {
// 创建HashMap集合对象,明确泛型类型
HashMap<Student, NativePlace> hashMap = new HashMap<Student, NativePlace>();
// 调用方法获取学生的籍贯信息
getStudentInformation(hashMap);
}
public static void getStudentInformation(HashMap<Student, NativePlace> hashMap) {
// 向集合中添加学生籍贯信息
hashMap.put((new Student("黎明", 23)), (new NativePlace("山东", "济南", "历下区")));
hashMap.put((new Student("李钢", 29)), (new NativePlace("山东", "淄博", "沂源")));
hashMap.put((new Student("王磊", 26)), (new NativePlace("山东", "聊城", "茌平")));
hashMap.put((new Student("黎明", 23)), (new NativePlace("山东", "济南", "历下区")));
// 获取key的Set视图(键的Set集合),并进行迭代
Iterator<Student> it = hashMap.keySet().iterator();
while (it.hasNext()) {
Student key = it.next();
NativePlace value = hashMap.get(key);
System.out.println(key + " " + value);
}
}
}
/*
* 学生类,属性有姓名和年龄
*/
class Student {
// 私有化成员变量
private String name;
private int age;
// 构造方法初始化对象
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
// 重写hashCode方法,为了保证唯一性,如果相同就再重写equals方法
@Override
public int hashCode() {
return name.hashCode() + age * 13;
}
// 重写equals方法
@Override
public boolean equals(Object obj) {
// 判断是不是同一个对象
if (this == obj)
return true;
Student stu = (Student) obj;
return this.name.equals(stu.name) && this.age == stu.age;
}
// 重写toString方法
@Override
public String toString() {
return "姓名:" + name + " 年龄:" + age;
}
}
/*
* 籍贯类,属性有省份、城市、乡镇
*/
class NativePlace {
// 私有化成员变量:省份、城市、乡镇
private String province;
private String city;
private String village;
// 构造方法初始化对象
public NativePlace(String province, String city, String village) {
super();
this.province = province;
this.city = city;
this.village = village;
}
// 重写toString方法
@Override
public String toString() {
return " 籍贯: " + province + "省" + city + "市" + village + "县";
}
}
有收获就给个赞呗
|
|