排序不可比元素的列表 [英] Sorting a list of non-comparable elements

查看:66
本文介绍了排序不可比元素的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天有人问我这个面试问题:

Today I was asked this interview question:


如果我有一个人名称 age salary 字段的类,以及我将这个 Person 的100个新实例放在 ArrayList 中,然后执行 Collections.sort (列表),那么该列表将按什么参数排序?

If I have a Person class with name, age and salary fields, and I put 100 new instances of this Person in an ArrayList, and then do Collections.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 Comparables. Specifically, a List<T> where T implements Comparable<? super T>.

这篇关于排序不可比元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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