gpt4 book ai didi

java - 为什么 Collections.sort() 只适用于列表而不适用于集合?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:01:09 25 4
gpt4 key购买 nike

为什么 Collections.sort() 仅适用于 List 而不适用于 Set?有什么特别的原因吗?

最佳答案

大多数(但不是全部)Set 实现没有顺序的概念,因此 Collections.sort 不支持它们作为所有的。如果你想要一个有顺序概念的集合,你可以使用像 TreeSet 这样的东西。 :

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

或者一个LinkedHashSet :

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)

关于java - 为什么 Collections.sort() 只适用于列表而不适用于集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17325954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com