Why does Collections.sort() apply only for lists a

2019-02-17 04:20发布

Why does Collections.sort() apply only for Lists and not for Sets? Is there any particular reason?

5条回答
该账号已被封号
2楼-- · 2019-02-17 04:57

A set is not ordered. You can use SortedSet. Or you can create a List from the set and sort it.

查看更多
forever°为你锁心
3楼-- · 2019-02-17 05:09

Most (but not all) Set implementations do not have a concept of order, so Collections.sort does not support them as a whole. If you want a set with a concept of order, you can use something like a 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.

Or a 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)

查看更多
我只想做你的唯一
4楼-- · 2019-02-17 05:09

List is an ordered set of elements while Set is not which implies that none of Set elements will have any sequence number. So you can't sort it.

查看更多
不美不萌又怎样
5楼-- · 2019-02-17 05:12

A Set, by definition, has no order.

查看更多
做自己的国王
6楼-- · 2019-02-17 05:19

A Set is not a List. While a List, by contract, is supposed to retain insertion order (otherwise, methods such as .get(someindex) would not make any sense), this is not the case for a Set. You have no method to get an element at a particular index in a Set! Neither do you have methods to insert at a particular position etc.

More specifically, the ordering of Set is undefined; however, implementations of Set can add ordering constraints.

For instance:

  • LinkedHashSet retains insertion ordering;
  • TreeSet maintains natural ordering of its elements, either because its elements implement Comparable, or because you supply a Comparator.

If you sorted a LinkedHashSet, you would break its insertion ordering guarantee!

查看更多
登录 后发表回答