Java中Comparable与Comparator的原理及使用

本文介绍了Java中自然排序和客户化排序的概念,详细讲解了Comparable接口用于对象的自然排序,Comparator接口则用于实现更灵活的客户化排序。通过示例展示了如何在自定义类中实现Comparable接口进行排序,以及如何定义Comparator进行排序。同时,文章探讨了Comparable与Comparator的排序原理,以及两者之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在排序任务中,可将其分为自然排序:数值大小、字符Asics码序列的排序;客户化排序:也即通过自定义的序列方式进行排序。

1. 自然排序

在JDK类库中,有一部分类实现了Comparable接口,如Integer Double和String等,如下Integer类实现了Comparable的接口,通过重写compareTo方法定义了排序的规则:

返回值 含义
-1 大于
0 等于
1 小于
    //Integer类中部分源码;实现了Comparable的接口,可以进行自然排序
    public final class Integer extends Number implements Comparable<Integer> {
   
	    public int compareTo(Integer anotherInteger) {
   
	        return compare(this.value, anotherInteger.value);
	    }
	    
	    public static int compare(int x, int y) {
   
	        return (x < y) ? -1 : ((x == y) ? 0 : 1);
	    }
	}

JDK中实现了Comparable接口的类库

类名 排序方式
BigDecimal BigInteger Byte Double Float Integer Long Short 按数字大小排序
Character 按字符的Unicode值的数字大小排序
String 按字符中字符的Unicode值排序

注意:使用自然排序时只能向集合中加入同类型的对象,并且这些对象的类必须实现Comparable接口 。

2. 客户化排序

2.1使用Comparable接口

对自己定义的类,设置规则实现排序。如:对学生信息先按照学号升序,再按照成绩降序排列;
创建学生类:

public class A04_Comparable_Student implements Comparable<A04_Comparable_Student> {
   
	
	private String name;
	private int id;
	private float score;
	public A04_Comparable_Student(String name, int id, float score) {
   
		// TODO Auto-generated constructor stub
		this.name = name;
		this.id = id;
		this.score = score;
	}
	/**
	 * @return the id
	 */
	public int getId() {
   
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
   
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public String getName(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值