经常会遇到这样的问题 我们将一组对象存放进List中去,然后我们希望,存放在List当中的对象是根据对象中的某一个属性进行排序的。例如,很经典的例子,ArrayList存放了Person对象,person有很多属性,name,age,gender等等。
这时我们希望存放在ArrayList当中的Person按照年龄排序。方法如下:
先声明一个Person 类
package arraysort;
public class Person {
private String name = "";
private String gender="";
private int age = 0;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
然后我们实现自己的比较规则,MyComparator
package arraysort;
import java.util.Comparator;
public class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Person person1 = (Person)o1;
Person person2 = (Person)o2;
if(person1.getAge() < person2.getAge()){//通过这里设定排列顺序
return 1;
}else{
return 0;
}
}
}
最后测试一下 我们的比较规则 是否可以如所愿
package arraysort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ArrayListSort {
public static void main(String args[]){
List list = new ArrayList<Person>();
list.add(new Person("Crazy2",34));
list.add(new Person("Crazy1",35));
list.add(new Person("Crazy3",33));
list.add(new Person("Crazy5",31));
list.add(new Person("Crazy4",32));
for(int i=0; i < list.size();i++){
Person p = (Person)list.get(i);
System.out.println("Name:" + p.getName() + "Age:" + p.getAge());
}
System.out.println("The Above is unsorted.");
Comparator comp = new MyComparator();
Collections.sort(list,comp);
for(int i=0; i < list.size();i++){
Person p = (Person)list.get(i);
System.out.println("Name:" + p.getName() + "Age:" + p.getAge());
}
}
}
执行结果:
Name:Crazy2Age:34
Name:Crazy1Age:35
Name:Crazy3Age:33
Name:Crazy5Age:31
Name:Crazy4Age:32
The Above is unsorted.
Name:Crazy1Age:35
Name:Crazy2Age:34
Name:Crazy3Age:33
Name:Crazy4Age:32
Name:Crazy5Age:31
参考网络资源。