java排序比较_java比较排序Comparable和Comparator

1       比较排序Comparable和Comparator

1.1      接口作用说明

Comparable和Comparator都是用来实现对象的比较、排序,对比时需要实现Comparable或Comparator接口,Comparator位于java.util包下,而Comparable位于java.lang包下。

实现类需要实现Comparable接口,在类的内部实现compareTo方法。如 String、Integer已经实现了Comparable接口,自己就可以完成比较大小操作;而Comparator接口,需要定义一个对比类,实现Comparator接口。然后将需要的比较的两个实现类对象传入比较器的compare函数进行比较。前者自己继承接口,内部实现比较;后者外部实现接口,作为一个比较器,将实现类传入对比类方法中。如果比较的方法在很多类中需要用到,就自己写个比较类实现Comparator接口,这样当要比较的时候,把实现了Comparator接口的比较类传过去,省得重复造轮子。

1.2      接口的定义

(1)Comparable的定义:

package java.lang;

import java.util.*;

public interface Comparable {

public int compareTo(T o);

}

(2)Comparator的定义如下:

package java.util;

public interface Comparator {

int compare(T o1, T o2);

boolean equals(Object obj);

}

实现Comparable接口要重写compareTo方法,实现Comparator需要重写 compare 方法。

1.3      比较

1.3.1   实现Comparable接口,实现compareTo方法

class Student implements Comparable{

public String name;

public int age;

public Student(String name, int age){

this.name = name;

this.age = age;

}

@Override

public int compareTo(Object o) {

Student student = (Student)o;

return this.age- student.age          }

1.3.2   实现Comparator接口,实现compare方法

定义比较器类

class NameSorter implements Comparator{

@Override

public int compare(Object o1, Object o2) {

Student s1 =(Student) o1;

Student s2 =(Student) o2;

return s1.name.compareTo(s2.name);

}

class Student implements Comparator{

public String name;

public int age;

public Student(String name, int age){

this.name = name;

this.age = age;

}

@Override ///按名称排序

public int compare(Object o1, Object o2) {

Student s1 =(Student) o1;

Student s2 =(Student) o2;

return s1.name.compareTo(s2.name);

1.3.3   比较使用实例

(1)Comparable比较

使用实例:

Student stuA=new Student(“A”,10);

Student stuB=new Student(“B”,11);

If(stuB.compareTo(stuA)>0){}

(2)Comparator比较

NameSorter NameCompare =new NameSorter;

NameCompare.compare(stuA,stuB);

1.4      排序

(1)Comparable排序

ArrayList students = new ArrayList<>();

Students.add(stuA);

Students.add(stuB);

Collections.sort(students);//按照年龄排序, students 列表中的对象已经实现了Comparable接口,会根据CompareTo方法进行排序。Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,就像一个工具类,服务于Java的Collection框架。

(2)Comparator排序

students.sort(new NameSorter());//传入比较器,按照名称排序

或者调用Collections的静态方法,传入比较器。

Collections.sort(students, new NameSorter());

自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取:

百度云盘下载地址:

链接:https://pan.baidu.com/s/1swkQzCIKI3g3ObcebgpIDg

提取码:mc8l

微信公众号获取最新的软件和视频介绍

QStockView

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值