首页 > 编程语言 > 详细

java二叉树 TreeMap集合测试

时间:2015-10-10 18:36:24      阅读:269      评论:0      收藏:0      [点我收藏+]
import java.util.*;
/**
学生Student 地址addr 属性:姓名,年龄
注:姓名和年龄相同为同一个学生
保证学生唯一性

对学生按年龄升序排序
*/
class Student implements Comparable{
    private int age;
    private String name;
    public int compareTo(Object obj){
        
        Student s = (Student)obj;
        int num =  this.getName().compareTo(s.getName());
        if(num==0){
            return    this.getAge()-s.getAge();    
        }
        else 
            return num;
    }
    
    //唯一性判断
    public int hashCode(){
         return     name.hashCode()+age*12;
    }
    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;    
    }    
    Student(String name,int age){
        this.age = age;
        this.name = name;    
    }        
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;    
    }
}

//自定义比较器
class MyCom implements Comparator<Student>{//接收比较对象的类型是学生类
    public int compare(Student s1 ,Student s2 ){
        int num = s1.getAge()-s2.getAge();    
        if(num==0){
            return s1.getName().compareTo(s2.getName());
        }
        else 
            return num;
    }
}

class TreeMapTest{
    public static void main(String[]args){
        TreeMap<Student,String> hm = new TreeMap<Student,String>();
        hm.put(new Student("李四1",21),"北京");
        hm.put(new Student("李四2",22),"广州");
        hm.put(new Student("李四2",25),"广州");
        hm.put(new Student("李四3",23),"杭州");
        Set<Student> ky = hm.keySet();
      Iterator<Student> it=ky.iterator();
      while(it.hasNext()){
          Student stu = it.next();
          String addr = hm.get(stu);
          System.out.println("学生姓名:"+stu.getName()+",年龄:"+stu.getAge()+",地址:"+addr);    
      }      
    }
}


本文出自 “司马囧” 博客,转载请与作者联系!

java二叉树 TreeMap集合测试

原文:http://9274590.blog.51cto.com/9264590/1701628

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!