java中的接口是类吗
216
2023-07-27
java实现List中对象排序的方法
本文实例讲述了java实现List中对象排序的方法。分享给大家供大家参考,具体如下:
package com.test;
import javoXpGKZsGla.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class NewsManager {
/**
* @param args
*/
public static void main(String[] args) {
List newss=getNewsList();
for(int i=0;i { News news=(News)newss.get(i); System.out.println("id:"+news.getId()); System.out.println("title:"+news.getTitle()); System.out.println("hits:"+news.getHits()); } } public static List getNewsList() { List list=new ArrayList(); News news1=new News(); news1.setHits(1); news1.setId(1); news1.setTitle("test1"); list.add(news1); News news2=new News(); news2.setHits(7); news2.setId(2); news2.setTitle("test2"); list.add(news2); News news3=new News(); news3.setHits(3); news3.setId(3); news3.setTitle("test3"); list.add(news3); News news4=new News(); news4.setHits(5); news4.setId(4); news4.setTitle("test4"); list.add(news4); // 按点击数倒序 Collections.sort(list, new Comparator public int compare(News arg0, News arg1) { int hits0 = arg0.getHits(); int hits1 = arg1.getHits(); if (hits1 > hits0) { return 1; } else if (hits1 == hits0) { return 0; } else { return -1; } } }); return list; } } 希望本文所述对大家Java程序设计有所帮助。
{
News news=(News)newss.get(i);
System.out.println("id:"+news.getId());
System.out.println("title:"+news.getTitle());
System.out.println("hits:"+news.getHits());
}
}
public static List getNewsList()
{
List list=new ArrayList();
News news1=new News();
news1.setHits(1);
news1.setId(1);
news1.setTitle("test1");
list.add(news1);
News news2=new News();
news2.setHits(7);
news2.setId(2);
news2.setTitle("test2");
list.add(news2);
News news3=new News();
news3.setHits(3);
news3.setId(3);
news3.setTitle("test3");
list.add(news3);
News news4=new News();
news4.setHits(5);
news4.setId(4);
news4.setTitle("test4");
list.add(news4);
// 按点击数倒序
Collections.sort(list, new Comparator
public int compare(News arg0, News arg1) {
int hits0 = arg0.getHits();
int hits1 = arg1.getHits();
if (hits1 > hits0) {
return 1;
} else if (hits1 == hits0) {
return 0;
} else {
return -1;
}
}
});
return list;
}
}
希望本文所述对大家Java程序设计有所帮助。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~