Sort an array of objects
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String names[] = { "W", "M", "N", "K" };
Arrays.sort(names);
for (int i = 0; i < names.length; i++) {
String name = names[i];
System.out.print("name = " + name + "; ");
}
Person persons[] = new Person[4];
persons[0] = new Person("W");
persons[1] = new Person("M");
persons[2] = new Person("N");
persons[3] = new Person("K");
Arrays.sort(persons);
for (int i = 0; i < persons.length; i++) {
Person person = persons[i];
System.out.println("person = " + person);
}
}
}
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;
}
}
Related examples in the same category