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:50

Here is a quick summary of the order characteristics of the standard Set implementations available in Java:

  1. keep the insertion order: LinkedHashSet and CopyOnWriteArraySet (thread-safe)
  2. keep the items sorted within the set: TreeSet, EnumSet (specific to enums) and ConcurrentSkipListSet (thread-safe)
  3. does not keep the items in any specific order: HashSet (the one you tried)

For your specific case, you can either sort the items first and then use any of 1 or 2 (most likely LinkedHashSet or TreeSet). Or alternatively and more efficiently, you can just add unsorted data to a TreeSet which will take care of the sorting automatically for you.

查看更多
\"骚年 ilove
3楼-- · 2019-01-03 06:51

Only SortedSet can do the ordering of the Set

查看更多
Explosion°爆炸
4楼-- · 2019-01-03 06:53

As many of the members suggested use LinkedHashSet to retain the order of the collection. U can wrap your set using this implementation.

SortedSet implementation can be used for sorted order but for your purpose use LinkedHashSet.

Also from the docs,

"This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation:"

Source : http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

查看更多
叼着烟拽天下
5楼-- · 2019-01-03 06:54

Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:

Set myOrderedSet = new LinkedHashSet(mySet);
查看更多
\"骚年 ilove
6楼-- · 2019-01-03 06:54

Normally set does not keep the order, such as HashSet in order to quickly find a emelent, but you can try LinkedHashSet it will keep the order which you put in.

查看更多
▲ chillily
7楼-- · 2019-01-03 06:57

The Set interface itself does not stipulate any particular order. The SortedSet does however.

查看更多
登录 后发表回答