- import java.util.*;
- //学生类
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- //构造函数初始化学生
- Student(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Student stu)
- {
- //按学生的年龄排序,如果年龄相等就按姓名字典序排序
- int num = new Integer(this.getAge()).compareTo(new Integer(stu.getAge()));
- if(num == 0)
- return this.getName().compareTo(stu.getName());
- //否则就按年龄排序
- return num;
- }
- //计算学生对象的哈希地址
- public int hashCode()
- {
- return name.hashCode()+age*37;
- }
- public boolean equals(Object obj)
- {
- //如果不是学生对象,抛出类型转换异常
- if(!(obj instanceof Student))
- throw new ClassCastException("不能转换成Student类型");
- //类型转换
- Student stu = (Student)obj;
- //比较学生对象姓名和年龄,去除重复元素
- return this.getName().equals(stu.getName()) && this.getAge()==stu.getAge();
- }
- public void setName(String name)
- {
- this.name =name;
- }
- public String getName()
- {
- return name;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return name+"....."+age;
- }
- }
- //主类用public修饰
- public class MapTest
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String[] args)
- {
- //1 创建hashMap映射
- HashMap<Student,String> hm = new HashMap<Student,String>();
- //2 添加学生对象为键和对应的地址为值
- hm.put(new Student("Jack",20),"北京");
- hm.put(new Student("mike",19),"兰州");
- hm.put(new Student("mike",19),"兰州");
- hm.put(new Student("Tom",25),"广州");
- hm.put(new Student("Alice",17),"上海");
- hm.put(new Student("Jimmy",21),"长沙");
- //3 取出学生和对应地址
- getWay_2(hm);
- }
- //3.2 第二种方式从Map中取出所有键值
- public static void getWay_2(HashMap<Student,String> hm)
- {
- sop("第二种方式从Map中取出所有键值");
- //1 把所有的映射关系存入Set<Map.Entry<Student,String>>
- Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
- //2 获取迭代器
- for(Iterator<Map.Entry<Student,String>> it = entrySet.iterator(); it.hasNext(); )
- {
- //3 迭代取出映射项
- Map.Entry<Student,String> me = it.next();
- //4 获取学生
- Student stu = me.getKey();
- //5 获取地址
- String addr = me.getValue();
- //6打印获取结果
- sop(stu.toString()+"......"+addr);
- }
- }
- }
复制代码
|
|