import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
*对ArrayList进行排序案例及代码实现
*/
public class CollectionDemo2 {
public static void main(String[] args) {
List<Person2>data=new ArrayList<Person2>();
data.add(new Person2("jack", 25, 10));
data.add(new Person2("rose", 10, 7));
data.add(new Person2("mary", 24, 6));
data.add(new Person2("jary", 30, 5));
data.add(new Person2("xiaoming", 23, 11));
Collections.sort(data,new Comparator<Person2>() {
@Override
public int compare(Person2 o1, Person2 o2) {
if (o1.getAge()-o2.getAge()>0) {
return 1;
}else if (o1.getAge()-o2.getAge()<0) {
return -1;
}
return o1.getName().compareTo(o2.getName());
//因为string已经实现了Comparator这个方法,有compareTo进行比较
}
});
for (Person2 p : data) {
//使用增强for循环输出
System.out.println(p);
}
}
}
class Person2{
private String name ;
private int age;
private int id;
public Person2(String name, int age, int id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person2 [name=" + name + ", age=" + age + ", id=" + id + "]";
}
}