集册 Java实例教程 实现可比较接口的类

实现可比较接口的类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

557
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
实现可比较接口的类
/**来自 
 NowJava.com - 时代Java**/

import java.util.Arrays;


public class Main {

   public static void main(String[] args) {

    Person[] persons = new Person[] {

        new Person("A", "AA"),

        new Person("B", "BB"),

        new Person("C", "CC")};

    

    System.out.println("Before sorting...");

    print(persons);

    

    // Sort the persons list

    Arrays.sort(persons);

    

    System.out.println("\nAfter sorting...");

    print(persons);

  }

   

  public static void print(Person[] persons) {

    for(Person person: persons){
    /**
    n o w j a   v  a . c o m - 时  代  Java
    **/

      System.out.println(person);

    }

  }

}


class Person implements Comparable<Person> {


    private String firstName;

    private String lastName;


    public Person(String firstName, String lastName) {

        this.firstName = firstName;

        this.lastName = lastName;

    }


    public String getFirstName() {

        return firstName;

    }


    public void setFirstName(String firstName) {

        this.firstName = firstName;

    }


    public String getLastName() {

        return lastName;

    }


    public void setLastName(String lastName) {

        this.lastName = lastName;

    }


    // Compares two persons based on their last names. If last names are

    // the same, use first names

    public int compareTo(Person anotherPerson) {

 
展开阅读全文