Java对象的比较

背景:

在开发的过程中我们可能会遇到一些数字的比较,对数字进行排序。但是但我们遇到对象比较的时候,比如商品的综合排序,学生的综合排序。这样就需要我们自定义比较方法。

我们分为两种,一种是该对象实现了一个Comparable接口,另一个是利用Comparator比较器。

代码:

import java.util.*;

public class TestCompare {

    public static void main(String[] args){
        ArrayList<Student> studentList = new ArrayList<>();
        ArrayList<Person> peopleList = new ArrayList<>();
        Student[] students = new Student[10];
        Person[] people = new Person[10];
        Random random = new Random();
        for(int i = 0 ; i <10 ;i++){
            int age = random.nextInt(100);
            String personName = "kyc-person"+i;
            String studentName = "kyc-student"+i;
            Person person = new Person(personName,age);
            Student student = new Student(studentName,age);
            studentList.add(student);
            peopleList.add(person);
            students[i] = student;
            people[i] = person;
        }
        System.out.println("初始studentList:"+studentList);
        System.out.println("初始peopleList:"+peopleList);
        printMyList("初始students:",students);
        printMyList("初始people:",people);
        //1.该类实现了Comparable接口,排序方法
        Collections.sort(studentList);
        System.out.println("排序studentList:"+studentList);

        Arrays.sort(students);
        printMyList("排序students",students);


        //2.该类没有实现Comparable接口,排序方法
        Comparator<Person> comparator = Comparator.comparingInt(Person::getAge);

        Collections.sort(peopleList,comparator);
        System.out.println("排序peopleList:"+peopleList);

        Arrays.sort(people,comparator);
        printMyList("排序people:",people);
    }

    private static void printMyList(String string, Object[] objects) {
        System.out.print(string);
        for (int i = 0 ; i < objects.length; i++){
            System.out.print(objects[i]+" ");

        }
        System.out.println();
    }

}


class Person {
    private String name;
    private int age;

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

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return this.name+":"+this.age;
    }
}

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

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

    @Override
    public int compareTo(Student student) {
        return this.age-student.age;
    }

    @Override
    public String toString() {
        return this.name+":"+this.age;
    }
}

 输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

康雨城

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

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

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

打赏作者

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

抵扣说明:

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

余额充值