Java中Comparable接口的意义和用法学习笔记

一、为何需要实现Comparable接口

我们知道Collections类中包含很多对实现Collection接口容器各种操作的静态方法,最常用的莫过于排序(Collections.sort(List l))。

下面是个简答的例子:

public class Compare1{

      public static void f(){

         ArrayList arr = new ArrayList();

         arr.add(10);

         arr.add(23);

         arr.add(7);

         System.out.println(arr);

         Collections.sort(arr);

         System.out.println(arr);

   }

}

若想用Collections.sort()方法对List中的元素进行排序时需要注意的是List里存放的元素对应的类必须已经实现了Comparable接口。

二、Comparable接口简介

Comparable接口内部只有一个要重写的关键的方法,为:

int compareTo(T o);

该方法只返回一个int型的值,例如 i = x.compareTo(y) ,如果i = 0,则表明x和y在排位上是相等的(并非意味着x.equals(y) = true, 但是jdk api上强烈建议这样处理)。

如果返回数值 i>0,则意味 x>y,反之若 i<0,意味x<y。

自定义类实现Comparable接口举例:

import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable
{
    private String name;
    private int ranking;
    
    public Student(String name, int ranking)
    {
        this.name = name;
        this.ranking = ranking;
    }

    public String toString()
    {
        return this.name+":"+this.ranking;
    }

    public int compareTo(Object o)
    {
        Student s = (Student)(o);
        return this.ranking-s.ranking;
    }
}

public class Compare2()
{
    public static void f()
    {
        ArrayList arr = new ArrayList();
        arr.add(new Student("Jack",10));
        arr.add(new Student("Bill",23));
        arr.add(new Student("Rudy",7));
        System.out.println(arr);
        Collectoins.sort(arr);
        System.out.println(arr);    
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值