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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© LJZkevin 中级黑马   /  2014-7-19 18:35  /  779 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. TreeMap<String,Student > map = new TreeMap< String,Student>(
  2.                                  new Comparator<Student>() {
  3.                                  public int compare(Student s1, Student s2) {
  4.                                
  5.                                  int num = s1.getAge() - s2.getAge();
  6.                                
  7.                                  int num2 = num == 0 ? (s1.getName().compareTo(s2
  8.                                  .getName())) : num;
  9.                                
  10.                                  return num2;
  11.                                  }
  12.                                
  13.                                  });
复制代码

1 个回复

倒序浏览
楼主,你代码那边的三目运算符那样写有问题的,还有定义比较器的时候,最好是重新再定义一个类去实现comparator接口,这样的代码会比较好维护.
  1. package cn.test;

  2. import java.util.Comparator;


  3. public class ComparatorByAge implements Comparator {

  4.         public int compare(Object o1, Object o2) {
  5.                 Student s1 = (Student)o1;
  6.                 Student s2 = (Student)o2;
  7.                 int temp = s1.getAge() - s2.getAge();
  8.                 return temp == 0?s1.getName().compareTo(s2.getName()):temp;
  9.         }

  10. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马