利用Collections工具类可以实现对Arraylist数组排序,代码如下,其中Person类实现了comparable接口
ArrayList<Person> list=new ArrayList<Person>();
Person person1 =new Person("zhangsan", 14);
Person person2=new Person("zhangsan", 13);
list.add(person1);
list.add(person2);
Collections.sort(list);
for (Person person : list) {
System.out.println(person.getName()+person.getAge());
}
public class Person implements Comparable{
private String name;
private int age;
Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Object o) {
Person person=(Person)o;
int num=this.name.compareTo(person.name);
if(num==0){
return new Integer(this.age).compareTo(person.age);
}
return num;
}
}
|