什么是Comparable

public interface Comparable<T> {
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
* -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
* implies that <tt>x.compareTo(y)</tt> must throw an exception iff
* <tt>y.compareTo(x)</tt> throws an exception.)
*
* <p>The implementor must also ensure that the relation is transitive:
* <tt>(x.compareTo(y)&gt;0 &amp;&amp; y.compareTo(z)&gt;0)</tt> implies
* <tt>x.compareTo(z)&gt;0</tt>.
*
* <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
* implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
* all <tt>z</tt>.
*
* <p>It is strongly recommended, but <i>not</i> strictly required that
* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
* class that implements the <tt>Comparable</tt> interface and violates
* this condition should clearly indicate this fact. The recommended
* language is "Note: this class has a natural ordering that is
* inconsistent with equals."
*
* <p>In the foregoing description, the notation
* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
* <tt>0</tt>, or <tt>1</tt> according to whether the value of
* <i>expression</i> is negative, zero or positive.
*
* @param o the object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*
* @throws NullPointerException if the specified object is null
* @throws ClassCastException if the specified object's type prevents it
* from being compared to this object.
*/
public int compareTo(T o);
}
  • 是一个接口,定制排序规则
  • 对实现它的每个类的对象进行整体排序,里面compateTo方法是实现排序的具体方法
  • 比如TreeSet、SortedSet、Collections.sort()方法调用进行排序
  • String、Integer等类默认实现了这个接口,所以可以排序

compareTo方法

  • 用于比较次对象和指定对象的顺序,o为要比较的对象
  • 返回int类型
    • 大于0,表示this大于传进来的对象o,则往后排,即升序
    • 等于0,表示this等于传进来的对象o
    • 小于0,表示this小于传进来的对象o

案例

  根据学生的年龄进行排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet; public class TestCom {
public static void main(String[] args) {
Set<Student> studentSet = new TreeSet<>();
studentSet.add(new Student("jack", 32));
studentSet.add(new Student("tom", 22));
studentSet.add(new Student("mary", 35));
studentSet.add(new Student("tim", 11));
studentSet.add(new Student("tony", 49));
studentSet.add(new Student("dd", 30));
System.out.println(studentSet);
System.out.println("==============================");
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("jack", 32));
studentList.add(new Student("tom", 22));
studentList.add(new Student("mary", 35));
studentList.add(new Student("tim", 11));
studentList.add(new Student("tony", 49));
studentList.add(new Student("dd", 30));
System.out.println(studentList);
Collections.sort(studentList);
System.out.println(studentList);
}
} class Student implements Comparable {
private int age;
private String name; public void setAge(int age) {
this.age = age;
} public int getAge() {
return age;
} public void setName(String name) {
this.name = name;
} public String getName() {
return name;
} public Student(String name, int age) {
this.name = name;
this.age = age;
} @Override
public String toString() {
return "Student{" + "age=" + age + ", name='" + name + '\'' + '}';
} @Override
public int compareTo(Object o) {
if (o instanceof Student) {
Student student = (Student) o;
return this.age - student.age;
}
// 返回的数是0代表两个对象相同
return 0;
}
}

Java 集合元素排序接口Comparable的更多相关文章

  1. Java集合中Comparator和Comparable接口的使用

    在Java集合中,如果要比较引用类型泛型的List,我们使用Comparator和Comparable两个接口. Comparable接口 -- 默认比较规则,可比较的 实现该接口表示:这个类的实例可 ...

  2. Java集合之Collection接口

    java的集合分为三大接口,分别是Collection,Map,Iterator,集合接口和类在java.util包中,此次主要介绍三大接口之一的Collection接口. 一些Collection允 ...

  3. java集合之Set接口

    Set集合通常不能记住元素添加的顺序,其他的操作和它的父接口基本相同.只是行为上有细微的差别,Set集合不能包含相同的元素.如果尝试添加相同的元素,调用add()方法将返回false,且新元素不能被加 ...

  4. Java集合框架——Map接口

    第三阶段 JAVA常见对象的学习 集合框架--Map集合 在实际需求中,我们常常会遇到这样的问题,在诸多的数据中,通过其编号来寻找某一些信息,从而进行查看或者修改,例如通过学号查询学生信息.今天我们所 ...

  5. Java集合框架——Set接口

    第三阶段 JAVA常见对象的学习 集合框架--Set接口 List集合的特点是有序的,可重复的,是不是存在这一种无序,且能保证元素唯一的集合呢?(HashSet )这就涉及到我们今天所要讲的Set集合 ...

  6. java集合进行排序的两种方式

    java集合的工具类Collections中提供了两种排序的方法,分别是: Collections.sort(List list) Collections.sort(List list,Compara ...

  7. Java集合及LIst接口

    一.集合的概念 1.概述: 在学习集合前,先回忆一下数组的一个特征---数组有固定的长度,定义一个数组: int[] array = new int[]; 而针对数据长度可变的情况,产生了集合, ja ...

  8. Java集合框架——List接口

    第三阶段 JAVA常见对象的学习 集合框架--List接口 按照集合框架的继承体系,我们先从Collection中的List接口开始学习 (一) 概述及功能(ArrayList演示) (1) 概述 L ...

  9. Java集合框架之接口Collection源码分析

    本文我们主要学习Java集合框架的根接口Collection,通过本文我们可以进一步了解Collection的属性及提供的方法.在介绍Collection接口之前我们不得不先学习一下Iterable, ...

  10. Java 集合之Collection 接口和遍历方法

    这几篇是我按网上的教程来实习的. URL: http://www.cnblogs.com/jbelial/archive/2013/03/27/2981395.html 打代码的感觉挻好的.. 注意在 ...

随机推荐

  1. C++ placement new学习

    通常创建对象使用new操作,但这样无法指定在具体某一块内存开辟空间创建对象.而如果 可以指定开辟空间的内存位置,我们可以编写内存池高效的复用同一个内存位置,这样可以避免系统频繁申请可用内存 所占用的时 ...

  2. Linux环境下:程序的链接, 装载和库[动态链接]

    静态链接库在程序编译阶段就完成了链接工作,完成链接后,依赖的库就都打入了可执行文件中,所以文件大小一般会比较大. 而动态库链接库是在程序运行时才被链接的,所以磁盘上只要保留一份副本,因此节约了磁盘空间 ...

  3. 异构数据源同步之数据同步 → datax 改造,有点意思

    开心一刻 去年在抖音里谈了个少妇,骗了我 9 万 后来我发现了,她怕我报警 她把她表妹介绍给我 然后她表妹又骗了我 7 万 DataX DataX 是什么,有什么用,怎么用 不做介绍,大家自行去官网( ...

  4. Istio(七):ServiceEntry,sidecar,Envoy Filter

    目录 一.模块概览 二.系统环境 三.ServiceEntry 四.sidecar 4.1 Sidecar 4.2 工作负载选择器 4.3 入口和出口监听器 五.Envoy Filter 5.1 En ...

  5. Linux之命令提示符的颜色设置

    1.临时设置 执行下面的命令: export PS1="[\[\e[34;1m\]\u@\[\e[0m\]\[\e[32;1m\]\H\[\e[0m\] \[\e[31;1m\]\w\[\e ...

  6. 音视频-YUV数据格式

    一.YUV格式 1)kCVPixelFormatType_420YpCbCr8PlanarFullRange = 'f420' 对应YUV I420格式 2)kCVPixelFormatType_42 ...

  7. 使用 TiDB Vector 搭建 RAG 应用 - TiDB 文档问答小助手

    本文首发至TiDB社区专栏:https://tidb.net/blog/7a8862d5 前言 继上一次<TiDB Vector抢先体验之用TiDB实现以图搜图>后,就迫不及待的想做一些更 ...

  8. C# 指针简单使用

    1. 使用unsafe C# 支持 unsafe 上下文,你可在其中编写不可验证的代码. 在 unsafe 上下文中,代码可使用指针.分配和释放内存块,以及使用函数指针调用方法. C# 中的不安全代码 ...

  9. 阿里bxet逆向

    声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 目标网站 x82y 分析过 ...

  10. react withRouter高阶组件

    作用:把不是通过路由切换过来的组件中,将react-router 的 history.location.match 三个对象传入props对象上 默认情况下必须是经过路由匹配渲染的组件才存在this. ...