本帖最后由 CHJ 于 2013-9-24 20:14 编辑
- class MyCompare implements Comparator
- {
- //重写Comparator中的compare方法,按姓名顺序排序
- public int compare(Object o1,Object o2)
- {
- //判断给定对象是否为Student类,否则抛异常
- if (!((o1 instanceof Student) && (o2 instanceof Student)))
- throw new RuntimeException("NotSuchTypeException");
- //将给定对象强转为Student类
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
- //比较名字,返回数值,相同则比较年龄
- int n = s1.getName().compareTo(s2.getName());
- if (n == 0)
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return n;
- }
- }
复制代码 return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
这行,我能写成 return s1.getAge() - s2.getAge(); 么
|