Person.java Source code

Java tutorial

Introduction

Here is the source code for Person.java

Source

import java.util.Arrays;
import java.util.Comparator;

class Person implements Comparable<Person> {
    public Person(String firstName, String surname) {
        this.firstName = firstName;
        this.surname = surname;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getSurname() {
        return surname;
    }

    public String toString() {
        return firstName + " " + surname;
    }

    public int compareTo(Person person) {
        int result = surname.compareTo(person.surname);
        return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
    }

    private String firstName;
    private String surname;
}

class ComparePersons implements Comparator<Person> {
    // Method to compare Person objects - order is descending
    public int compare(Person person1, Person person2) {
        int result = -person1.getSurname().compareTo(person2.getSurname());
        return result == 0 ? -person1.getFirstName().compareTo(person2.getFirstName()) : result;
    }

    // Method to compare with another comparator
    public boolean equals(Object collator) {
        if (this == collator) { // If argument is the same object
            return true; // then it must be equal
        }
        if (collator == null) { // If argument is null
            return false; // then it can't be equal
        }
        return getClass() == collator.getClass(); // Class must be the same for
                                                  // equal
    }
}

public class MainClass {
    public static void main(String[] args) {
        Person[] authors = { new Person("A", "S"), new Person("J", "G"), new Person("T", "C"), new Person("C", "S"),
                new Person("P", "C"), new Person("B", "B") };
        System.out.println("Original order:");
        for (Person author : authors) {
            System.out.println(author);
        }
        Arrays.sort(authors, new ComparePersons()); // Sort using comparator
        System.out.println("\nOrder after sorting using comparator:");
        for (Person author : authors) {
            System.out.println(author);
        }
        Arrays.sort(authors); // Sort using Comparable method
        System.out.println("\nOrder after sorting using Comparable method:");
        for (Person author : authors) {
            System.out.println(author);
        }
    }
}