Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created October 30, 2009 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jutememo/222206 to your computer and use it in GitHub Desktop.
Save jutememo/222206 to your computer and use it in GitHub Desktop.
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Person implements Comparable<Person> {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return this.name;
}
int getAge() {
return this.age;
}
public int compareTo(Person o) {
return new Integer(this.age).compareTo(o.getAge());
}
@Override
public String toString() {
return this.name + ":" + this.age;
}
public static void main(String[] args) {
System.out.println(new Person("Tarou", 10).compareTo(new Person("Saburou", 30)));
List<Person> persons = Arrays.asList(
new Person("Saburou", 30),
new Person("Jiro", 20),
new Person("Tarou", 10),
new Person("Hanako", 30));
Collections.sort(persons);
System.out.println(persons);
Collections.sort(persons, new Comparator<Person>() {
public int compare(Person o1, Person o2) {
int c = new Integer(o1.getAge()).compareTo(o2.getAge());
if (c != 0) {
return c;
} else {
return o1.getName().compareTo(o2.getName());
}
}
});
System.out.println(persons);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment