Java Set retain order?

2019-01-03 06:31发布

Does a Java Set retain order? A method is returning a Set to me and supposedly the data is ordered but iterating over the Set, the data is unordered. Is there a better way to manage this? Does the method need to be changed to return something other than a Set?

标签: java set order
12条回答
男人必须洒脱
2楼-- · 2019-01-03 06:32

From the javadoc for Set.iterator():

Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

And, as already stated by shuuchan, a TreeSet is an implemention of Set that has a guaranteed order:

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

查看更多
Fickle 薄情
3楼-- · 2019-01-03 06:35

The Set interface does not provide any ordering guarantees.

Its sub-interface SortedSet represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet. They are TreeSet and ConcurrentSkipListSet.

In addition to the SortedSet interface, there is also the LinkedHashSet class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.

查看更多
做自己的国王
4楼-- · 2019-01-03 06:37

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order.

查看更多
We Are One
5楼-- · 2019-01-03 06:43

LinkedHashSet is what you need.

查看更多
等我变得足够好
6楼-- · 2019-01-03 06:45

To retain the order use List or a LinkedHashSet.

查看更多
Lonely孤独者°
7楼-- · 2019-01-03 06:46

Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?

查看更多
登录 后发表回答