Java对象的比较

背景:

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

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

代码:

import java.util.*;

public class TestCompare {

    public static void main(String[] args){
        ArrayList studentList = new ArrayList<>();
        ArrayList 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 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{
    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;
    }
}

 输出结果

Java对象的比较_第1张图片

你可能感兴趣的:(java,java从挨骂到转正)