将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。
import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.TreeMap; import cn.itcast.bean.Student; public class TreeMapTest { /** * @param args */ public static void main(String[] args) { /* * * 需求: * 将学生对象和归属地的映射关系存储到HashMap集合中,对学生对象按照年龄排序。并全部取出。 * 学生对象中包含着姓名和年龄这样的属性。 * 归属地:这里仅用字符串表示即可。 * * 思路: * 1,对学生对象进行描述。同姓名同年龄视为同一人。 * */ TreeMap<Student,String> tm = new TreeMap<Student,String>(new Comparator<Student>(){ public int compare(Student s1,Student s2){ int temp = s1.getName().compareTo(s2.getName()); return temp==0?s1.getAge()-s2.getAge():temp; } }); tm.put(new Student("xiaoming1",28), "北京"); tm.put(new Student("xiaoming7",23), "天津"); // tm.put(new Student("xiaoming7",23), "西藏"); tm.put(new Student("xiaoming2",25), "河北"); tm.put(new Student("xiaoming0",24), "河南"); //用keyset()取出。 // Iterator<Student> it = tm.keySet().iterator(); Set<Student> keySet = tm.keySet(); Iterator<Student> it = keySet.iterator(); while(it.hasNext()){ Student key = it.next(); String addr = tm.get(key); System.out.println(key.getName()+"::::"+key.getAge()+":::"+addr); } } } package cn.itcast.bean; public class Student implements Comparable<Student>{ private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } /** * 定义Student的hashCode的方法。 */ public int hashCode(){ final int NUMBER = 37; return name.hashCode()+age*NUMBER; } /** * 定义Student的equals方法。 */ public boolean equals(Object obj){ if(this == obj) return true; if(!(obj instanceof Student)) throw new ClassCastException("类型不匹配,无法比较"); Student stu = (Student)obj; return this.name.equals(stu.name) && this.age == stu.age; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } @Override public int compareTo(Student o) { int temp = this.age - o.age; return temp==0?this.name.compareTo(o.name):temp; } }
|