为什么我不能使用 Comparator 对基元进行排序?
由于 Java 5 具有自动装箱功能,为什么我不能使用 Comparator 对基元进行排序? int
不会被包装成 Integer
吗?
As Java 5 have autoboxing, why I can't use Comparator to sort primitives? An int
wouldn't be wrapped into a Integer
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Arrays.sort(..)
有专门的重载来对原始数组进行排序。如果除了标准规则之外您还需要任何特殊的排序规则,恐怕您必须使用自动装箱。除此之外,您还必须将数组转换为
Integer[]
,因为int[]
不会自动装箱。如果您不是在谈论数组,而是在谈论集合 - 那么您别无选择 - 集合只能保存对象。
Arrays.sort(..)
have dedicated overloadings for sorting primitive arrays.If you need any special sorting rules apart from the standard ones, I'm afraid you'd have to use autoboxing. In addition to that, you'd have to transform your array to
Integer[]
, becauseint[]
is not autoboxed.And if you are not talking about arrays, but about collections - then you have no choice - collections can hold only objects.
因为您无法使用原始类型参数化
Comparator
或任何其他参数化类型。是的,这非常烦人...您无法创建
List
或Map
等,并且您无法编写通用方法适用于对象类型和基元。您必须为 8 种基本类型中的每一种类型提供专用方法。但这就是我们自 Java 1 以来就一直坚持的设计。责怪 James Gosling ;-)正如 Bozho 指出的,
Arrays.sort(...)
提供了您需要的所有排序方法。Because you cannot parameterise a
Comparator<T>
-- or any other parameterised type -- with a primitive type.Yes this is massively annoying... you can't make a
List<int>
or aMap<String, boolean>
etc, and you can't write generic methods that work for both object types and primitives. You have to have dedicated methods for each of the 8 primitive types. But that's the design we've been stuck with since Java 1. Blame James Gosling ;-)As Bozho points out,
Arrays.sort(...)
provides all the sorting methods you need.从 java 17(或者可能更早)开始。错误消息的信息量更大。
因此,即使使用自动装箱,java 也无法正确推断类型。
As of java 17 (or possibly earlier. The error message is much more informative.
So even with autoboxing, java does not correctly infer the type.