【Java】:Comparable接口和Comparator接口

对象数组排序

通过年龄比较


Comparable接口

  • 此处运用到 comparable 接口,其内置方法为 comparaTo
  • 返回类型为整形
public interface Comparable<T> {
    public int compareTo(T o);
}

代码

class Student implements Comparable<Student> { //实现了Comparable接口的Student类
    public String name;
    public int age;

    public Student(String name, int age) { //构造方法
        this.name = name;
        this.age = age;
    }

    @Override  
    //重写Comparable接口内的comparaTo方法
    public int compareTo(Student o) {  
        return this.age - o.age;  //即调用方法的对象 - 参数对象
    }

    public static void main(String[] args) {
        Student student1 = new Student("John Smith", 10);
        Student student2 = new Student("Don Michael", 20);

        if(student1.compareTo(student2) > 0){   
        	//若student1 - student2 > 0,则打印:
            System.out.println("John Smith > Don Michael");
        } else if (student1.compareTo(student2) < 0) {   
        	//若student1 - student2 < 0,则打印:
            System.out.println("John Smith < Don Michael");
        }else{  
        	//若student1 - student2 = 0,则打印:
            System.out.println("John Smith = Don Michael");
        }
    }
}

//运行结果为:John Smith < Don Michael

通过姓名比较

字符串大小比较

  • 字符串的大小比较是指按照字典次序对单个字符或字符串进行比较大小的操作,一般都是以ASCII码值的大小作为字符比较的标准。

  • 比如 abcade 比较大小

    • 因为双方第一个字母相等,都是 a,所以比较对象均向后移一位
    • 由于 b < d,所以 abc < ade

代码

class Student implements Comparable<Student> {
    public String name;
    public int age;

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

    @Override
    public int compareTo(Student o) {
        if(this.name.compareTo(o.name) > 0){  //即调用方法的对象 - 参数对象
            return 1;
        } else if (this.name.compareTo(o.name) < 0) {
            return -1;
        }else {
            return 0;
        }
    }

    public static void main(String[] args) {
        Student student1 = new Student("John Smith", 10);
        Student student2 = new Student("Don Michael", 20);

        if(student1.compareTo(student2) > 0){
        	//若student1 - student2 > 0,则打印
            System.out.println("John Smith > Don Michael");
        } else if (student1.compareTo(student2) < 0) {
            //若student1 - student2 < 0,则打印
            System.out.println("John Smith < Don Michael");
        }else{
        	//若student1 - student2 = 0,则打印
            System.out.println("John Smith = Don Michael");
        }
    }
}

对比

  • 对两个类的重写方法进行对比,可以发现问题:
    • Comparable 这个接口具有局限性,一但这个类写死了,后期就无法进行修改
    • 可以理解为,写死的就是一个默认的比较方式
    • 由此,我们可以使用一个新的接口 Comparator

比较器——Comparator接口

  • Comparator接口返回类型也为整形
  • 其内部有很多内置方法
public interface Comparator<T> { //三处 T 必须都得一样
	int compare(T o1, T o2);
	//还有很多其他方法...
}
年龄比较器
import java.util.Comparator;

class Student {
    public String name;
    public int age;

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

public class AgeComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;  
    }

    public static void main(String[] args) {
        Student student1 = new Student("John Smith", 18);
        Student student2 = new Student("Don Michael", 28);

        AgeComparator ageComparator = new AgeComparator();
        if(ageComparator.compare(student1, student2) < 0) {
        	//若student1.age < student2.age,则打印:
            System.out.println("John Smith < Don Michael");
        }else if(ageComparator.compare(student1, student2) > 0) {
        	//若student1.age > student2.age,则打印:
            System.out.println("John Smith > Don Michael");
        }else {
        	//若student1.age == student2.age,则打印:
            System.out.println("John Smith = Don Michael");
        }
    }
}
姓名比较器
import java.util.Comparator;

class Student {
    String name;
    int age;

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

public class AgeComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);    
    }

    public static void main(String[] args) {
        Student student1 = new Student("John Smith", 23);
        Student student2 = new Student("Don Michael", 13);

        if(ageComparator.compare(student1, student2) == 0){
        	//若student1.name == student2.name,则打印:
            System.out.println("John Smith = Don Michael");
        }else if(ageComparator.compare(student1, student2) < 0){
        	//若student1.age < student2.age,则打印:
            System.out.println("John Smith < Don Michael");
        }else {
        	//若student1.age > student2.age,则打印:
            System.out.println("John Smith > Don Michael");
        }
    }
}

  • 在比较器中,比较的对象可以按照需求动态修改,不是写死的
  • 所以比较器 Comparator 用起来更加方便
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个简单的Java Condition接口使用示例: 假设有一个共享的缓冲区,其中生产者线程可以将数据项添加到缓冲区中,而消费者线程可以从中移除数据项。缓冲区有一个最大容量,当缓冲区已满时,生产者线程需要等待直到缓冲区中有空间可以添加数据。同样,当缓冲区为空时,消费者线程需要等待直到有数据项可供消费。 可以使用Java的Condition接口来实现此类同步。以下是一个示例代码: ```java import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Buffer { private Queue<Integer> buffer; private int maxSize; private Lock lock; private Condition notFull; private Condition notEmpty; public Buffer(int maxSize) { this.maxSize = maxSize; buffer = new LinkedList<>(); lock = new ReentrantLock(); notFull = lock.newCondition(); notEmpty = lock.newCondition(); } public void put(int num) throws InterruptedException { lock.lock(); try { while (buffer.size() == maxSize) { notFull.await(); } buffer.offer(num); System.out.println("Produced " + num); notEmpty.signal(); } finally { lock.unlock(); } } public int take() throws InterruptedException { lock.lock(); try { while (buffer.size() == 0) { notEmpty.await(); } int num = buffer.poll(); System.out.println("Consumed " + num); notFull.signal(); return num; } finally { lock.unlock(); } } } ``` 在这个示例中,我们使用一个有限的缓冲区实现了一个简单的生产者-消费者模型。我们定义了一个缓冲区队列和一个最大容量。我们还使用了Java的Lock和Condition接口来确保线程之间的同步。 在构造函数中,我们初始化了缓冲区,锁和条件变量。我们使用ReentrantLock作为锁,使用newCondition()方法创建了两个条件变量:notFull和notEmpty。 在put()方法中,我们首先获取锁,然后使用while循环检查缓冲区是否已满。如果是,则调用notFull.await()方法将当前线程阻塞,直到缓冲区中有足够的空间可以添加新元素。如果缓冲区未满,则将新元素添加到缓冲区中,并通过notEmpty.signal()方法通知其他可能正在等待的消费者线程可以消费数据。最后,我们释放锁。 在take()方法中,我们首先获取锁,然后使用while循环检查缓冲区是否为空。如果是,则调用notEmpty.await()方法将当前线程阻塞,直到缓冲区中有可消费的元素。如果缓冲区不为空,则从缓冲区中取出一个元素,并通过notFull.signal()方法

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高乐高有点矮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值