现在的位置: 首页 > 综合 > 正文

根据对象里面的某个属性进行排序(Collections.sort())

2013年08月28日 ⁄ 综合 ⁄ 共 1533字 ⁄ 字号 评论关闭
Code:
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3. import java.util.Comparator;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6.   
  7. public class Test {  
  8.     private String name;  
  9.     private int age;  
  10.     public String getName() {  
  11.         return name;  
  12.     }  
  13.     public void setName(String name) {  
  14.         this.name = name;  
  15.     }  
  16.     public int getAge() {  
  17.         return age;  
  18.     }  
  19.     public void setAge(int age) {  
  20.         this.age = age;  
  21.     }  
  22.      
  23.     public static void main(String[] args){  
  24.         Test test1=new Test();  
  25.         test1.setAge(22);  
  26.         test1.setName("careers01");  
  27.         Test test2=new Test();  
  28.         test2.setAge(25);  
  29.         test2.setName("careers02");  
  30.         Test test3=new Test();  
  31.         test3.setAge(23);  
  32.         test3.setName("careers03");  
  33.         List<Test> list=new ArrayList<Test>();  
  34.         list.add(test1);list.add(test2);list.add(test3);  
  35.          
  36.         Collections.sort(list,new Comparator(){  
  37.             public int compare(Object o1, Object o2) {  
  38.                 // TODO Auto-generated method stub  
  39.                 Test t1=(Test)o1;  
  40.                 Test t2=(Test)o2;  
  41.                 int age1 =t1.getAge();  
  42.                 int age2 =t2.getAge();  
  43.                 if(age1==age2)return 0;  
  44.                 if(age1>age2)return -1;  
  45.                 return 1;  
  46.         }});  
  47.         Iterator<Test> it=list.iterator();  
  48.         while(it.hasNext()){  
  49.             System.out.println("it.next()=="+it.next().getAge());  
  50.         }  
  51.          
  52.     }  
  53.      
  54. }  

抱歉!评论已关闭.