public class Person implements Comparable
{
private String name;
private int age;
public Person(String n, int a)
{name = n;
age = a;
}
public int getAge()
{return age;
}
public int compareTo(Object o) // needs to be Object parameter to implement comparable
{if (age > ((Person)o).getAge())
return 1;
if (age < ((Person)o).getAge())
return -1;
return 0;
}
public String toString()
{return name + " " + age;
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.io.*;
import java.util.Arrays;
public class SortObjects
{
public static void main(String[] args)
{
Person[ ] peeps = new Person[7];
peeps[0] = new Person("Joe",12);
peeps[1] = new Person("Sue",30);
peeps[2] = new Person("Tom",45);
peeps[3] = new Person("Mike",10);
peeps[4] = new Person("Ellen",60);
peeps[5] = new Person("Larry",3);
peeps[6] = new Person("Mary",37);
Arrays.sort(peeps); //use the built-in sorting routine
for (int i = 0; i < peeps.length; i++)
System.out.println(peeps[ i ]); // toString is implemented
// Person implements Comparable around age field
}
}