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[] = {"Bob", "Mallory", "Alice", "Carol"};
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.util.support;

public class Person implements Comparable<Person> {
    private String name;

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

    public int compareTo(Person person) {
        return this.name.compareTo(person.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("Bob");
persons[1] = new Person("Mallory");
persons[2] = new Person("Alice");
persons[3] = new Person("Carol");
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.util;

import org.kodejava.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String[] names = {"Bob", "Mallory", "Alice", "Carol"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person[] persons = new Person[4];
        persons[0] = new Person("Bob");
        persons[1] = new Person("Mallory");
        persons[2] = new Person("Alice");
        persons[3] = new Person("Carol");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Alice, Bob, Carol, Mallory]
Persons = [Alice, Bob, Carol, Mallory]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.