A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 潘际昌 中级黑马   /  2013-11-23 14:56  /  1586 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 潘际昌 于 2013-11-24 00:53 编辑

import java.util.*;



public class Test
{

        public static void main(String[] args) {
                TreeSet<Student> ts=new TreeSet<Student>(new myComparator());
                ts.add(new Student("zhangsan1",20,97));
                ts.add(new Student("zhangsan2",21,99));
                ts.add(new Student("zhangsan5",25,95));
                ts.add(new Student("zhangsan3",19,98));
                ts.add(new Student("zhangsan7",15,90));
                Iterator<Student> it = ts.iterator();
                while(it.hasNext())
                {
                        Student s= it.next();
                        System.out.println(s.getName()+","+s.getAge()+","+s.getScore());
                }
                                
        }

}
class myComparator implements Comparator<Student>
{
        public int compare(Student s1,Student s2)
        {
               
               
        
                int num=new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));
                if(num==0)
                {
                        return s1.getName().compareTo(s2.getName());
                }
                return num;
        }
        
        
}
class Student
{
        String name;
        int age;
        int score;
        Student(String name,int age,int score)
        {
                this.name=name;
                this.age=age;
                this.score=score;
        }
        String getName()
        {
                return name;
        }
        int getAge()
        {
                return age;
        }
        int getScore()
        {
                return score;
        }
        
        
}比较器里面,为什么 s1.getName().compareTo(s2.getName());字符型可以直接比较,而int型        
int num=new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));还需要new Interger()呢?

评分

参与人数 1技术分 +1 黑马币 +4 收起 理由
枫儿 + 1 + 4 神马都是浮云

查看全部评分

4 个回复

倒序浏览

字符串就是对象,可以直接compareTo进行比较,int型是基本数据类型,得装箱成Integer对象类型,才可以用compareTo进行比较,所以要new Ingeger()      
API里面compareTo(T o) 方法
          比较此对象与指定对象的顺序。

评分

参与人数 1黑马币 +4 收起 理由
枫儿 + 4 很给力!

查看全部评分

回复 使用道具 举报
楼上已经给出了解释,还有既然是int型为什么要用comparTo来比较呢
  1. int num = s1.getScore()-s2.getScore();
  2. return num==0? s1.getName().compareTo(s2.getName()):num;
复制代码
这样不就行了
回复 使用道具 举报
String类和Integer类中都有compareTo方法,Integer类中的compareTo方法是在数字上比较两个 Integer 对象,String类中的compareTo方法是按字典顺序比较两个字符串。这里是因为自定义比较器,且是按成绩排序, return num=new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));是返回成绩大小,如果成绩相等则按姓名字典顺序排序,即return s1.getName().compareTo(s2.getName());
回复 使用道具 举报
getName中的compareTo调用的是String里边的compareTo方法
而int类型的没有compareTo方法只有Integer类型的才有而int和Integer的自动拆箱和自动装箱是在-128-127之间     因为你比较的是变量jvm无法判断是不是能自动转换    所以要用new Integer()来进行比较
一般的int和Integer类型的直接相减就行了啊    干嘛还要使用compareTo方法呢
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马