本帖最后由 公子-醉香 于 2013-12-19 11:03 编辑
- package day01;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class TryReturn {
- public static void main(String [] args){
- TreeMap<Student , String> tm = new TreeMap<Student , String>();
- tm.put(new Student("lise1" , 21), "beijing");
- tm.put(new Student("lise1" , 21), "beijing");
- tm.put(new Student("alisi4" ,24), "wuhan");
- tm.put(new Student("lisi" , 21), "tianjin");
- tm.put(new Student("lisi2" , 22), "shanghai");
- Set<Map.Entry<Student , String>> entrySet =
- tm.entrySet();
- for(Iterator<Map.Entry<Student , String>> it = entrySet.iterator() ; it.hasNext();)
- {
- Map.Entry<Student, String> me = it.next();
- Student stu = me.getKey();
- String addr = me.getValue();
- System.out.println(stu + "::" + addr);
- }
- }
-
-
- }
- 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 s)
- {
- int num = new Integer(this.age).compareTo
- (new Integer(s.age));
- if(num == 0)
- return this.name.compareTo(s.name);
- return num;
- }
-
- public int hashCode()
- {
- return name.hashCode() + age*34;
- }
-
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s = (Student)obj;
- return this.name.equals(s.name) && this.age == s.age;
-
- }
- public String getName()
- {
- return name;
- }
-
- public int getAge()
- {
- return age;
- }
- @Override
- public String toString() {
- return "Student [name=" + name + ", age=" + age + ", hashCode()="
- + hashCode() + ", getName()=" + getName() + ", getAge()="
- + getAge() + ", getClass()=" + getClass() + ", toString()="
- + super.toString() + "]";
- }
-
- }
复制代码 |
|