Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Sorting Arrays of Objects with Comparable

array

  • Please log in to reply
4 replies to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 02 November 2009 - 01:55 PM

Sorting Objects

The java.util packages contains a class Array that contains methods for sorting arrays. It can sort arrays of any type and uses a modified quick sort algorithm to sort the array.

Let us take a look at sorting objects. To do this we have to lean about the Comparable interface. The comparable interface describes how two objects should be compared. This interface is what allows us to sort arrays.

First we have to create a class. For the purpose of this tutorial we will create a Person class with three fields name, age, and height.

class Person {
	int age;
	int height;
	String name;

	Person(int age, int height, String name) {
		this.age = age;
		this.height = height;
		this.name = name;
	}
}

This code is very simple. It is a template to create a bunch of Person objects. We need an array of them so we will create an array of people.

Person[] aroPeople = new Person[4];

aroPeople[0] =new Person(17,100,"James");
aroPeople[1] = new Person(18,94,"John");
aroPeople[2] = new Person(16,120,"Chris");
aroPeople[3] = new Person(17,89,"Bob");

We populate an array of Person objects. Now we want to sort this array and output some information about it.

First let us look at how we are going to do some outputting.

Add this method to the Person class.

public String toString() {
	return name + " is " + age + " years old and has a height of " + height;
}

Whenever we pass an object to the System.out.println method the toString method is called and that is what is outputted.

Example:

System.out.println(aroPeople[0]);

Output:

James is 17 years old and has a height of 100


Now that we have output down, all we have left to do is tell Java how we want to sort the array. This is what we need the Comparable interface for.

Change this line:

class Person {

to

class Person implements Comparable<Person> {

This tells Java that we are going to be comparing Person objects. Now we have to implement the compare to method which tells us how we want to do some sorting.

public int compareTo(Person p) {
        
        return 0;
}

Add that method to the class declaration. We will return 1 if the object we are comparing to is greater than the current object, -1 if the object we are comparing to is less than the current object. Otherwise, we will return 0 (indicating that they are equal).

Returning 1 will sort in ascending order, returning -1 will sort in descending order. This approach allows us to sort by more than one field.

We want to sort in ascending order by age, then descending order by height. Only if age is equal do we want to sort by height.

Change the compare to method to this:

public int compareTo(Person p) {

        if (age < p.age) {
            return -1;
        }

        if (age > p.age) {
            return 1;
        }

        // only sort by height if age is equal
        if (height > p.height) {
            return -1;
        }

        if (height < p.height) {
            return 1;
        }

        return 0;
    }

This gives you a very fast and quick way to sort an array of objects by any fields in any order that you want.

Now to do the sorting and outputting:

Arrays.sort(aroPeople);
for (int i=0;i<aroPeople.length;i++) {
            System.out.println(aroPeople[i]);
}

All the details of the sorting is handled by Java and you don't need to know why it works. Hope this helps!
  • -1

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 04 November 2009 - 05:10 AM

Well done, Chili! +rep
  • 0

#3 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 04 November 2009 - 05:38 PM

Very Nice +rep :)
  • 0

#4 Phazic

Phazic

    CC Lurker

  • Just Joined
  • Pip
  • 7 posts

Posted 26 October 2010 - 12:24 AM

Thanks for the nice tutorial, made me get this in like 5minutes x)
  • 0

#5 Java_

Java_

    CC Newcomer

  • Member
  • PipPip
  • 13 posts

Posted 01 November 2010 - 11:06 AM

Thanks inspired me to do something with my applet. +Rep
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download