javable之Comparable

本文介绍了在Java中,如何使自定义类型支持集合类中的排序算法,如Collections.sort()、Collections.min()和Collections.max()。通过实现Comparable接口或传入Comparator比较器,可以按照自定义规则对List中的对象进行排序和查找最大最小值。示例代码展示了Dog类的年龄升序排序和查找最大最小年龄的Dog对象。
摘要由CSDN通过智能技术生成

我们知道,在Java的集合类中是有一些可复用的算法的,比如
Collections.sort()从小到大排序,Collections.min(),最小值Collections.max()最大值,
这些对于list操作来说都是非常常见的,也经常需要用到

1 List strings = new ArrayList();
2 strings.add(“ab”);
3 strings.add(“cc”);
4 strings.add(“bc”);
5 Collections.sort(strings);
6 String max =Collections.max(strings);
7 String min =Collections.min(strings);
8 System.out.println(strings);//[ab, bc, cc]
9 System.out.println(max);//cc
10 System.out.println(min);//ab
11
12 List integers = new ArrayList();
13 integers.add(2);
14 integers.add(1);
15 integers.add(3);
16 Collections.sort(integers);
17 Integer max1 =Collections.max(integers);
18 Integer min1 =Collections.min(integers);
19 System.out.println(integers);//[1, 2, 3]
20 System.out.println(max1);//3
21 System.out.println(min1);//1

那么问题就来了,例子中的String,Integ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值