Comparable 和 Comparator的理解

简介: Comparable是一个排序接口 此接口给实现类提供了一个排序的方法,此接口有且只有一个方法

对Comparable 的解释

Comparable是一个排序接口

此接口给实现类提供了一个排序的方法,此接口有且只有一个方法

public int compareTo(T o);

compareTo方法接受任意类型的参数,来进行比较

list或者数组实现了这个接口能够自动的进行排序,相关类的方法有Collections.sort(),Arrays.sort();

SortedMap 接口的key内置了compareTo方法来进行键排序,SortedSet 也是内置了compareTo方法作为其内部元素的比较手段

compareTo()方法与equals()方法的比较

compareTo()方法不同于equals()方法,它的返回值是一个int类型

int a = 10 , b = 20 , c = 30 , d = 30;

a.compareTo(b) // 返回 -1 说明 a 要比 b 小
c.compareTo(b) // 返回 1 说明 c 要比 b 大
d.compareTo(c) // 返回 0 说明 d 和c 相等

而equals 方法返回的是boolean 类型

x.equals(y) // true 说明x 与 y 的值 相等 , false 说明x 与 y 的值 不相等

代码

Comparable 更像是一个内部排序接口,一个类实现了Comparable比较器,就意味着它本身支持排序;可以用Collections.sort() 或者 Arrays.sort() 进行排序

public class Student implements Comparable<Student>{

String name;
int record;

public Student(){}
public Student(String name,int record){
this.name=name;
this.record=record;
}

public boolean equals(Student student) {
// 拿名字和成绩进行对比
return name.equals(student.name)
&&record == student.record;
}

@Override
public int compareTo(Studentstu) {
// 调用String 类的compareTo方法,返回值 -1,0,1
return this.name.compareTo(stu.name);
}

get and set...
}


public class ComparableTest{

public static void main(String[] args) {
List<Student> studentList = Arrays.asList(new Student("liming", 90),
new Student("xiaohong", 95),
new Student("zhoubin", 88),
new Student("xiaoli", 94)
);
// 排序前
System.out.println(studentList);
Collections.sort(studentList);
// 排序后
System.out.println(studentList);

for(Student student : studentList){
System.out.println(student.equals(new Student("xiaohong", 95)));
}
}
}

输出:

liming = 90, xiaohong = 95, zhoubin = 88, xiaoli = 94

false true false false

compareTo()方法抛出异常

public int compareTo(To);

NullPointerException : 如果 对象o为null,抛出空指针异常

ClassCastException: 如果需要类型转换之后进行比较,可能会抛出ClassCastException


对Comparator 的解释

Comparator 相当于一个比较器,作用和Comparable类似,也是使用Collections.sort() 和 Arrays.sort()来进行排序,也可以对SortedMap 和 SortedSet 的数据结构进行精准的控制,你可以不用实现此接口或者Comparable接口就可以实现次序比较。 TreeSet 和 TreeMap的数据结构底层也是使用Comparator 来实现。不同于Comparable ,比较器可以任选地允许比较null参数,同时保持要求等价关系。

Comparator比较器的方法

int compare(T o1, T o2);

compare() 方法的用法和Comparable 的 compareTo() 用法基本一样,这个方法不允许进行null值比较,会抛出空指针异常

boolean equals(Object obj);

jdk1.8 之后又增加了很多新的方法

33.jpg

很多都是关于函数式编程的,在这里先不做讨论了

代码实现

public class AscComparator implements Comparator<Student>{

@Override
public int compare(Student stu1, Student stu2) {

// 根据成绩降序排列
return stu1.getRecord() - stu2.getRecord();
}

}

public class ComparatorTest{

public static void main(String[] args) {
List<Student> studentList = Arrays.asList(new Student("liming", 90),
new Student("xiaohong", 95),
new Student("zhoubin", 88),
new Student("xiaoli", 94)
);
// 1. 可以实现自己的外部接口进行排序
Collections.sort(studentList,new AscComparator());

System.out.println(studentList);

// 2、 可以匿名内部类实现自定义排序
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
return stu2.getRecord() -stu1.getRecord();
}
});
System.out.println(studentList);
}
}

也可以使用Arrays.sort()进行排序,不过针对的数据结构是数组。


Comparable 和 Comparator 的对比

1、Comparable 更像是自然排序

2、Comparator 更像是定制排序

同时存在时采用 Comparator(定制排序)的规则进行比较。

对于一些普通的数据类型(比如 String, Integer, Double…),它们默认实现了Comparable 接口,实现了 compareTo 方法,我们可以直接使用。

而对于一些自定义类,它们可能在不同情况下需要实现不同的比较策略,我们可以新创建 Comparator 接口,然后使用特定的 Comparator 实现进行比较。

            </div>
目录
相关文章
|
7天前
|
数据采集 人工智能 安全
|
17天前
|
云安全 监控 安全
|
3天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:七十、小树成林,聚沙成塔:随机森林与大模型的协同进化
随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并结合它们的预测结果来提高准确性和稳定性。其核心思想包括两个随机性:Bootstrap采样(每棵树使用不同的训练子集)和特征随机选择(每棵树分裂时只考虑部分特征)。这种方法能有效处理大规模高维数据,避免过拟合,并评估特征重要性。随机森林的超参数如树的数量、最大深度等可通过网格搜索优化。该算法兼具强大预测能力和工程化优势,是机器学习中的常用基础模型。
286 164
|
2天前
|
机器学习/深度学习 自然语言处理 机器人
阿里云百炼大模型赋能|打造企业级电话智能体与智能呼叫中心完整方案
畅信达基于阿里云百炼大模型推出MVB2000V5智能呼叫中心方案,融合LLM与MRCP+WebSocket技术,实现语音识别率超95%、低延迟交互。通过电话智能体与座席助手协同,自动化处理80%咨询,降本增效显著,适配金融、电商、医疗等多行业场景。
295 155
|
4天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:六十九、Bootstrap采样在大模型评估中的应用:从置信区间到模型稳定性
Bootstrap采样是一种通过有放回重抽样来评估模型性能的统计方法。它通过从原始数据集中随机抽取样本形成多个Bootstrap数据集,计算统计量(如均值、标准差)的分布,适用于小样本和非参数场景。该方法能估计标准误、构建置信区间,并量化模型不确定性,但对计算资源要求较高。Bootstrap特别适合评估大模型的泛化能力和稳定性,在集成学习、假设检验等领域也有广泛应用。与传统方法相比,Bootstrap不依赖分布假设,在非正态数据中表现更稳健。
229 113
|
10天前
|
SQL 自然语言处理 调度
Agent Skills 的一次工程实践
**本文采用 Agent Skills 实现整体智能体**,开发框架采用 AgentScope,模型使用 **qwen3-max**。Agent Skills 是 Anthropic 新推出的一种有别于mcp server的一种开发方式,用于为 AI **引入可共享的专业技能**。经验封装到**可发现、可复用的能力单元**中,每个技能以文件夹形式存在,包含特定任务的指导性说明(SKILL.md 文件)、脚本代码和资源等 。大模型可以根据需要动态加载这些技能,从而扩展自身的功能。目前不少国内外的一些框架也开始支持此种的开发方式,详细介绍如下。
775 5