Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Sorting a Collection containing user defined Objects

import java.util.Arrays; class Person implements Comparable<Person> {   public Person(String firstName, String surname) {     this.firstName = firstName;     this.surname = 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; } public class MainClass {   public static void main(String[] args) {     Person[] authors = { new Person("A", "B"),                           new Person("C", "D"),                          new Person("E", "F"),                           new Person("Z", "Y"),                          new Person("X", "T"),                           new Person("O", "R") };     Arrays.sort(authors);     System.out.println("\nThe cast is ascending sequence is:\n");     for (Person person : authors) {       System.out.println(person);     }   } } The cast is ascending sequence is: A B C D E F O R X T Z Y