使用ArrayList来存储Person对象,使用Collection类所提供的静态sort方法来按要
使用ArrayList来存储Person对象,使用Collection类所提供的静态sort方法来按要求对ArrayList进行排序。Person对象包含姓名,年龄和id...
使用ArrayList来存储Person对象,使用Collection类所提供的静态sort方法来按要求对ArrayList进行排序。Person对象包含姓名,年龄和id。要求按照年龄从小到大排列年龄一样再按姓名排列输出
展开
1个回答
展开全部
按照你的要求编写的Java程序如下
import java.util.ArrayList;
import java.util.Collections;
class Person implements Comparable{
int id;
String name;
int age;
public Person(){}
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Object o) {
if(o instanceof Person){
Person p=(Person)o;
if(this.age<p.age)
return -1;
else if(this.age==p.age)
if(this.name.compareTo(p.name)<=0){
return -1;
}else{
return 1;
}
else{
return 1;
}
}
return 0;
}
}
public class PersonSort {
static ArrayList<Person> al=new ArrayList<Person>();
public static void main(String[] args) {
al.add(new Person(1001,"xiaoming",21));
al.add(new Person(1002,"xiaohong",22));
al.add(new Person(1003,"zhangsan",22));
al.add(new Person(1004,"lisi",22));
al.add(new Person(1005,"wangwu",23));
Collections.sort(al);
for(Person p:al){
System.out.println(p);
}
}
}
运行结果
Person [id=1001, name=xiaoming, age=21]
Person [id=1004, name=lisi, age=22]
Person [id=1002, name=xiaohong, age=22]
Person [id=1003, name=zhangsan, age=22]
Person [id=1005, name=wangwu, age=23]
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询