Collections.sort在任何类的java [英] Collections.sort in java for any class

查看:193
本文介绍了Collections.sort在任何类的java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java类问题

在C ++中,如果我们向向量添加一些类对象,我们可以通过指定一些函数来对列表进行排序:operator< ()或operator!=。

In C++ if we add some class objects to vector , we can sort the list by specifying some functions like operator<() or operator==() or operator!=.

我们需要在Java中为Collections.sort根据我们的愿望工作。

What do we need to do in java for Collections.sort to work according to our wishes

您可以实现 可比较的< T>

You implement Comparable<T>.

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29rel =nofollow> 集合。 sort

From the docs for Collections.sort:


按指定列表的升序排序,元素。列表中的所有元素都必须实现Comparable接口。此外,列表中的所有元素必须是相互可比的(即,e1.compareTo(e2)不能为列表中的任何元素e1和e2抛出ClassCastException。)

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

或者,如果你控制元素类型(例如你有一个 List< String> 并且您要应用自定义排序顺序)您实现 Comparator< T> ,并将其作为一个额外参数传递给 Collections.sort

Alternatively, if you don't control the element type (e.g. you've got a List<String> and you want to apply a custom sort order) you implement Comparator<T> and pass that in as an extra parameter to Collections.sort

这篇关于Collections.sort在任何类的java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆