第一种:
- import java.util.ArrayList;
- import java.util.Collections;
- public class Test {
- public static void main(String[] args) {
- ArrayList<Person> al = new ArrayList<Person>();
- al.add(new Person("lisi", 46));
- al.add(new Person("wangwu", 35));
- al.add(new Person("zhouqi", 25));
- al.add(new Person("sisan", 20));
- Collections.sort(al);
- for(Person p:al){
- System.out.println(p.getName()+"::"+p.getAge());
- }
- }
- }
- class Person implements Comparable<Person> {
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- @Override
- public int compareTo(Person o) {
- int num = new Integer(o.getAge()).compareTo(this.getAge());
- return num==0?o.getName().compareTo(this.getName()):num;
- }
- }
复制代码
第二种:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class Test {
- public static void main(String[] args) {
- ArrayList<Person> al = new ArrayList<Person>();
- al.add(new Person("lisi", 46));
- al.add(new Person("wangwu", 35));
- al.add(new Person("zhouqi", 25));
- al.add(new Person("sisan", 20));
- Collections.sort(al,new Comparator<Person>(){
- public int compare(Person o1, Person o2) {
- int num = new Integer(o2.getAge()).compareTo(o1.getAge());
- return num==0?o2.getName().compareTo(o1.getName()):num;
- }
-
- });
- for(Person p:al){
- System.out.println(p.getName()+"::"+p.getAge());
- }
- }
- }
- class Person{
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
复制代码 |