How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.example.util.support;

public class Person implements Comparable {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.name.compareTo(p.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Wayan");
persons[1] = new Person("Made");
persons[2] = new Person("Nyoman");
persons[3] = new Person("Ketut");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.example.util;

import org.kodejava.example.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person persons[] = new Person[4];
        persons[0] = new Person("Wayan");
        persons[1] = new Person("Made");
        persons[2] = new Person("Nyoman");
        persons[3] = new Person("Ketut");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Ketut, Made, Nyoman, Wayan]
Persons = [Ketut, Made, Nyoman, Wayan]