Why does Collections.sort()
apply only for List
s and not for Set
s? Is there any particular reason?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
A set is not ordered. You can use SortedSet. Or you can create a List from the set and sort it.
Most (but not all)
Set
implementations do not have a concept of order, soCollections.sort
does not support them as a whole. If you want a set with a concept of order, you can use something like aTreeSet
:Or a
LinkedHashSet
: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.
A Set, by definition, has no order.
A
Set
is not aList
. While aList
, 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 aSet
. You have no method to get an element at a particular index in aSet
! Neither do you have methods to insert at a particular position etc.More specifically, the ordering of
Set
is undefined; however, implementations ofSet
can add ordering constraints.For instance:
LinkedHashSet
retains insertion ordering;TreeSet
maintains natural ordering of its elements, either because its elements implementComparable
, or because you supply aComparator
.If you sorted a
LinkedHashSet
, you would break its insertion ordering guarantee!