Created
October 30, 2009 07:51
-
-
Save jutememo/222206 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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