Java对象比较器:Comparable接口与Comparator接口区别与理解

  
  相同:
  1.都需要继承接口后才能排序。
   2.都需要配合Collections.sort或者Arrays.sort的方法来排序,并都能支持自定义排序规则。
  主要区别:
    Comparable接口用在类的设计初期支持排序。
    Comparator接口用在类设计已经完成后,还想排序。
  总结:总体比较comparator比较灵活,具体场景灵活使用。

 

具体使用,详情代码如下链接:

  https://pan.baidu.com/s/1rXrhhpYRnIvQ7BaqbM78Sg

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class Comparators { public static java.util.Comparator getComparator() { return new java.util.Comparator() { public int compare(Object o1, Object o2) { if (o1 instanceof String) { return compare( (String) o1, (String) o2); } else if (o1 instanceof Integer) { return compare( (Integer) o1, (Integer) o2); } else if (o1 instanceof Person) { return compare( (Person) o1, (Person) o2); } else { System.err.println("未找到合适的比较器"); return 1; } } public int compare(String o1, String o2) { String s1 = (String) o1; String s2 = (String) o2; int len1 = s1.length(); int len2 = s2.length(); int n = Math.min(len1, len2); char v1[] = s1.toCharArray(); char v2[] = s2.toCharArray(); int pos = 0; while (n-- != 0) { char c1 = v1[pos]; char c2 = v2[pos]; if (c1 != c2) { return c1 - c2; } pos++; } return len1 - len2; } public int compare(Integer o1, Integer o2) { int val1 = o1.intValue(); int val2 = o2.intValue(); return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1)); } public int compare(Boolean o1, Boolean o2) { return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1)); } public int compare(Person o1, Person o2) { String firstname1 = o1.getFirstName(); String firstname2 = o2.getFirstName(); String lastname1 = o1.getLastName(); String lastname2 = o2.getLastName(); Boolean sex1 = o1.getSex(); Boolean sex2 = o2.getSex(); Integer age1 = o1.getAge(); Integer age2 = o2.getAge(); return (compare(firstname1, firstname2) == 0 ? (compare(lastname1, lastname2) == 0 ? (compare(sex1, sex2) == 0 ? (compare(age1, age2) == 0 ? 0 : compare(age1, age2)) : compare(sex1, sex2)) : compare(lastname1, lastname2)) : compare(firstname1, firstname2)); } }; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值