假设有一个ArrayList<Object[]>
包含其中的各种对象:
ArrayList<Object[]> list = new ArrayList<>();
list.add(new Object[]{"cat", (long)1422355945});
list.add(new Object[]{"dog", (long)1422355970});
list.add(new Object[]{"rat", (long)1422355900});
我们如何以相反的顺序首先Object
(String
)有效地对此列表进行排序?并在第二个Object
(long
)之后执行相同的操作?
答案 0 :(得分:1)
只需创建一个比较器,类似于以下示例:
List<Object[]> list = new ArrayList<>();
list.add(new Object[] { "cat", (long) 1422355945 });
list.add(new Object[] { "dog", (long) 1422355970 });
list.add(new Object[] { "rat", (long) 1422355900 });
Collections.sort(list, new Comparator<Object[]>() {
@Override
public int compare(Object[] o1, Object[] o2) {
int cmp1 = ((String) o1[0]).compareTo((String) o2[0]);
if (cmp1 == 0) {
return Long.compare((Long) o1[1], (Long) o2[1]);
}
return cmp1;
}
});