Java object-oriented programming practice-implementing the sorting of Comparable interface

This article will introduce how to use Java object-oriented programming to achieve the need to sort by name and age, and to implement the sorting of objects by implementing the Comparable interface.

  1. Define the PersonSortable class

First, we need to define a PersonSortable class, which contains a private name and a private age attributes to represent the person's name and age. Following is the code of PersonSortable class:

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

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

    public String toString() {
        return name + "-" + age;
    }

    public int compareTo(PersonSortable other) {
        int result = name.compareTo(other.getName());
        if (result == 0) {
            result = age - other.getAge();
        }
        return result;
    }
}
  1. Used in main function

In the main function, we can first enter an integer n, which means that we need to enter the names and ages of n people. Then, we can read in n rows of data through a loop, construct each row of data into a PersonSortable object, and put it into an array. Next, we can sort the array by calling the Arrays.sort method. The following is the code of the main function:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        PersonSortable[] persons = new PersonSortable[n];
        for (int i = 0; i < n; i++) {
            String name = scanner.next();
            int age = scanner.nextInt();
            persons[i] = new PersonSortable(name, age);
        }

        Arrays.sort(persons);

        for (PersonSortable person : persons) {
            System.out.println(person.toString());
        }

        System.out.println(Arrays.toString(PersonSortable.class.getInterfaces()));
    }
}

In the above code, we first input the integer n, then read in n rows of data through a loop, and constructed each row of data into a PersonSortable object and put it into the persons array. Next, we sort the persons array using the Arrays.sort method. Finally, we use the System.out.println method to output all interfaces implemented by PersonSortable.

  1. Summarize

This article introduces how to use Java object-oriented programming to implement sorting requirements by name and age, and to sort objects by implementing the Comparable interface. By learning the methods introduced in this article, readers can further master the basic knowledge of Java object-oriented programming and improve their programming abilities.

Guess you like

Origin blog.csdn.net/qq_61433567/article/details/131140161