根据对象里面的某个属性进行排序(Collections.sort())
2013年08月28日
⁄ 综合
⁄ 共 1533字 ⁄ 字号
小 中 大
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.List;
-
- public class Test {
- private String name;
- private int age;
- 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 static void main(String[] args){
- Test test1=new Test();
- test1.setAge(22);
- test1.setName("careers01");
- Test test2=new Test();
- test2.setAge(25);
- test2.setName("careers02");
- Test test3=new Test();
- test3.setAge(23);
- test3.setName("careers03");
- List<Test> list=new ArrayList<Test>();
- list.add(test1);list.add(test2);list.add(test3);
-
- Collections.sort(list,new Comparator(){
- public int compare(Object o1, Object o2) {
-
- Test t1=(Test)o1;
- Test t2=(Test)o2;
- int age1 =t1.getAge();
- int age2 =t2.getAge();
- if(age1==age2)return 0;
- if(age1>age2)return -1;
- return 1;
- }});
- Iterator<Test> it=list.iterator();
- while(it.hasNext()){
- System.out.println("it.next()=="+it.next().getAge());
- }
-
- }
-
- }