Collections中的元素按多个属性排序

darkattack 2006-04-06 08:47:24
有没有现成的包,可以对collection中的元素按指定的属性(1个或多个),最好能像SQL那样的ORDER BY语句,可以指定不同属性的升序和降序等。
...全文
331 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ysd126 2006-04-29
  • 打赏
  • 举报
回复
这样就可以了:
class Compa implements Comparator
{
public int compare(Object a,Object b)
{
if(a instanceof Integer && b instanceof Integer)
{
if(((Integer)a).intValue() > ((Integer)b).intValue())
{
return 1;
}
else
{
if(((Integer)a).intValue() < ((Integer)b).intValue())
{
return -1;
}
}
}
return 0;
}
}
public class Test
{
public static void main(String[] args)
{
Compa a = new Compa();
TreeSet set = new TreeSet(a);
set.add(new Integer(100));
set.add(new Integer(-100));
set.add(new Integer(200));
set.add(new Integer(150));

Object value[] = set.toArray();
for(int i = 0 ;i<value.length;i++)
{
System.out.println(value[i]);
}
}
}
做鸡真好吃 2006-04-29
  • 打赏
  • 举报
回复
MM~
xiaogaozxm83 2006-04-28
  • 打赏
  • 举报
回复
不是所有的collection都能排序的
只有list接口的可以
set接口的就不行
你要实现comparable 接口
重写hashcode equals 的方法 和compareTo的方法

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧