为什么我不能使用 Comparator 对基元进行排序?

Why I can't use Comparator to sort primitives?

提问人:The Student 提问时间:12/30/2010 更新时间:4/12/2023 访问量:5244

问:

由于 Java 5 具有自动装箱功能,为什么我不能使用 Comparator 对原语进行排序?不会被包装成一个?intInteger

Java 排序 包装器 自动装箱

评论

0赞 Peter Lawrey 12/30/2010
比较器是使用泛型定义的,泛型不处理基元。但是,Arrays.sort() 不接受 Comparator...也许你可以说明你想做什么。
0赞 The Student 12/30/2010
@Peter Lawrey 刚刚为 SCJP 考试而学习。并想知道 Comparator 和包装有什么问题..

答:

7赞 Bozho 12/30/2010 #1

Arrays.sort(..)具有用于对基元数组进行排序的专用重载。

如果除了标准规则之外,您还需要任何特殊的排序规则,恐怕您必须使用自动装箱。除此之外,您还必须将数组转换为 ,因为不会自动装箱。Integer[]int[]

如果你不是在谈论数组,而是在谈论集合 - 那么你别无选择 - 集合只能保存对象。

评论

1赞 Peter Lawrey 12/30/2010
而且他们不使用比较器。
0赞 The Student 12/30/2010
我的疑问是为什么集合不能保存原语,如果我使用 int,它应该包装成一个 Integer,它是一个 Objects。
1赞 Peter Lawrey 12/30/2010
集合是使用泛型定义的,泛型不支持基元。您可以拥有像 trove.starlight-systems.com 这样的基元的集合,但这些集合不符合标准接口。
6赞 Neil Bartlett 12/30/2010 #2

因为不能使用基元类型参数化 -- 或任何其他参数化类型。Comparator<T>

是的,这非常烦人......你不能做一个或一个等等,你不能写出同时适用于对象类型和基元的泛型方法。您必须为 8 种基元类型中的每一种都有专用的方法。但这就是我们自 Java 1 以来一直坚持的设计。责怪詹姆斯·高斯林;-)List<int>Map<String, boolean>

正如 Bozho 所指出的,它提供了您需要的所有排序方法。Arrays.sort(...)

0赞 matt 4/12/2023 #3

从 java 17(或可能更早。错误消息的信息量要大得多。

jshell> int[] a = {1,2,3};
a ==> int[3] { 1, 2, 3 }

jshell> import java.util.Arrays;

jshell> Arrays.sort( a, (x, y)-> x - y);
|  Error:
|  no suitable method found for sort(int[],(x,y)->x - y)
|      method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable
|        (inference variable T has incompatible bounds
|          equality constraints: int
|          lower bounds: java.lang.Object)
|      method java.util.Arrays.<T>sort(T[],int,int,java.util.Comparator<? super T>) is not applicable
|        (cannot infer type-variable(s) T
|          (actual and formal argument lists differ in length))
|  Arrays.sort( a, (x, y)-> x - y);
|  ^---------^

因此,即使使用自动装箱,java 也无法正确推断类型。