排序不可比元素的列表 [英] Sorting a list of non-comparable elements
问题描述
今天有人问我这个面试问题:
Today I was asked this interview question:
如果我有一个
人
名称,age
和salary
字段的类,以及我将这个Person
的100个新实例放在ArrayList
中,然后执行Collections.sort (列表)
,那么该列表将按什么参数排序?
If I have a
Person
class withname
,age
andsalary
fields, and I put 100 new instances of thisPerson
in anArrayList
, and then doCollections.sort(list)
, then on what parameter will the list be sorted?
我知道我需要让 Person
类实现 Comparable
,然后覆盖 compareTo
,但是,如果我不这样做,会发生什么?
I understand that I need to have the Person
class implement Comparable
and then override compareTo
, but if I don't do that, what will happen?
推荐答案
它将无法编译:1参数版本的 Collections.sort
需要一个可比较
s的列表。具体来说, List< T>
其中 T
实现 Comparable< ;?超级T>
。
It wouldn't compile: the 1-argument version of Collections.sort
expects a list of Comparable
s. Specifically, a List<T>
where T
implements Comparable<? super T>
.
这篇关于排序不可比元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!