/**描述学生,每一个学生都有一个归属地学生Student 地址String类学生属性:姓名,年龄注意:姓名和年龄相同为同一个人需求:排除重复的学生,获取学生和其地址。*/import java.util.*;class Student implements Comparable {//要实现该接口,如果不实现,放在二叉树里会报错 private String name; private int age; Student(String name,int age){ this.name = name; this.age = age; } //防止出现对象放在二叉树集合时的情况 public int compareTo(Student t){ int num = new Integer(this.age).compareTo(new Integer(t.age)); if(num==0) return this.name.compareTo(t.name); return num; } //因为要判断排除重复的学生,学生唯一性是有姓名和年龄组成 public int hashCode(){ return name.hashCode()+age*3; } //复写判断方法 public boolean equals(Object obj){ //判断,如果传入的不是学生类,抛出异常。因为需求是要学生和学生比 if(!(obj instanceof Student)) throw new ClassCastException("不是学生类!"); Student st = (Student)obj;//向下转型 return this.name==st.name && this.age == st.age; } public String getName(){ return name; } public int getAge(){ return age; } //加上这一句不在打印hash值 public String toString(){ return "学生姓名:" + name + ",年龄:" + age; } }class MapTest{ public static void main(String[]args){ HashMap hm = new HashMap (); hm.put(new Student("李四1", 21),"北京1"); hm.put(new Student("李四1", 21),"北京5"); hm.put(new Student("李四2", 22),"北京2"); hm.put(new Student("李四3", 23),"北京3"); hm.put(new Student("李四4", 24),"北京4"); //2种取出方式 keySet方式 Set key = hm.keySet(); Iterator it = key.iterator(); while(it.hasNext()){ Student stu = it.next(); String addr =hm.get(stu); System.out.println(stu + ",地址:"+addr); } //entrySet方式 Set > me = hm.entrySet(); Iterator > iter = me.iterator(); while(iter.hasNext()){ Map.Entry me1 = iter.next(); Student stu = me1.getKey(); String addr = me1.getValue(); System.out.println(stu + ",地址:"+addr); } }}