展开全部
package test2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSort {
public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("王五",32)) ;
personList.add(new Person("张三",30)) ;
personList.add(new Person("赵六",33)) ;
personList.add(new Person("李四",31)) ;
personList.add(new Person("孙七",33)) ;
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
if(p1.age>p2.age){
return 1;
}
else if(p1.age<p2.age){
return 0;
}
else{
return p1.name.compareTo(p2.name) ; // 调用String中的compareTo()方法
}
}
});
System.out.println(personList);
}
}
class Person {
public String name ;
public int age ;
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String toString(){
return "姓名:" + this.name + ";年龄:" + this.age ;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSort {
public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("王五",32)) ;
personList.add(new Person("张三",30)) ;
personList.add(new Person("赵六",33)) ;
personList.add(new Person("李四",31)) ;
personList.add(new Person("孙七",33)) ;
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
if(p1.age>p2.age){
return 1;
}
else if(p1.age<p2.age){
return 0;
}
else{
return p1.name.compareTo(p2.name) ; // 调用String中的compareTo()方法
}
}
});
System.out.println(personList);
}
}
class Person {
public String name ;
public int age ;
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String toString(){
return "姓名:" + this.name + ";年龄:" + this.age ;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询