笑着生活  
思想大于技术...... 惟仁者为能以大事小,惟智者为能以小事大: Java之路——专注,研究,思考,总结
日历
<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
统计
  • 随笔 - 46
  • 文章 - 4
  • 评论 - 4
  • 引用 - 0

导航

留言簿(1)

随笔分类

随笔档案

文章分类

文章档案

相册

收藏夹

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ListSort {
     public static void main(String[] args){
         ArrayList list = new ArrayList();
         list.add(new Person("lcl",28));
         list.add(new Person("fx",23));
         list.add(new Person("wqx",29));
         Comparator comp = new Comparator(){
          public int compare(Object o1,Object o2) {
              Person p1=(Person)o1;
              Person p2=(Person)o2; 
             if(p1.age<p2.age)//或者比较name属性((p1.name.toString()).CompareTo.(p2.name.toString())>0)
                 return 1;
             else
                 return 0;
             }
        };
         Collections.sort(list,comp);
        
      
         for(int i = 0;i<list.size();i++){
             Person p = (Person)list.get(i);
             System.out.println(p.getName());
         } 
     }

     public  static class Person  {
        
         private int age;
         private String name;
        public Person(String name,int age){
         this.age = age;
         this.name = name;
        }
        public int getAge() {
      return age;
     }
     public void setAge(int age) {
      this.age = age;
     }
     public String getName() {
      return name;
     }
     public void setName(String name) {
      this.name = name;
     }
      
          }
   }

posted on 2008-10-28 20:50 999 阅读(613) 评论(1)  编辑  收藏 所属分类: J2SE
评论:
  • # re: 对List中存放的类通过其属性排序  yuanzi Posted @ 2012-04-26 14:35
    很有用,受教了,谢谢!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
 
Copyright © 999 Powered by: 博客园 模板提供:沪江博客