Class That Implements the Comparable Interface - Java Object Oriented Design

Java examples for Object Oriented Design:interface

Description

Class That Implements the Comparable Interface

Demo Code

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")};
    /*w w  w  .ja v  a 2 s  .  com*/
    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){
      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) {
        int diff = getLastName().compareTo(anotherPerson.getLastName());
        if (diff == 0) {
            diff = getFirstName().compareTo(anotherPerson.getFirstName());
        }
        return diff;
    }

    public String toString() {
        return getLastName() + ", " + getFirstName();
    }
}

Result


Related Tutorials