English 中文(简体)
Java Set 保留订单?
原标题:Java Set retain order?

Java Set 是否保留顺序? 一种方法正在将 Set 返回给我, 并且据推测数据被命令返回 Set, 但是在 Set 上循环, 数据没有顺序。 是否有更好的管理方法? 是否该方法需要更改来返回一个 Set 以外的东西?

最佳回答
问题回答

设置只是一个接口。 为了保留顺序, 您必须使用该接口和子界面排序的设置的具体执行方式, 例如 TreeSet 或链接的HashSet 。 您可以以这种方式包住您的设置 :

Set myOrderedSet = new LinkedHashSet(mySet);

要保留顺序使用 List LinkedHashSet

链接的HashSet 是 HashSet 的定序版本, 在所有元素中保持双链接列表。 如果您关心迭代命令, 请使用此类而非 HashSet 。

以下是 Java 中标准 < code> set 执行的顺序特性简略摘要 :

  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)

对于您的具体案例, 您可以先对项目进行排序, 然后使用任何 1 或 2 (很可能是 < code> LinkedHashSet 或 < code> TreeSet ) 。 或者, 或者和 < strong> 更有效率 , 您可以将未排序的数据添加到 < code> TreeSet 中, 这将自动处理您的排序 。

Set.terator () 的 Javadoc :

返回此集元素的迭代。 元素将不按特定顺序返回( 除非此组是某类中提供保证的例子 )。

“https://stackoverflow.com/uss/1381767/shuuchan>>shuuchan 所述,TreeSet 是执行有保证订单的Set :

使用自然顺序或根据设定设定时间提供的比较器对元素进行排序,视使用哪个建筑师而定。

通常设定不维持顺序, 如 HashSet 等, 以便快速找到一个精华, 但是您可以尝试链接 HashSet 来维持您设置的顺序 。

有两种不同的东西。

  1. Sort the elements in a set. For which we have SortedSet and similar implementations.
  2. Maintain insertion order in a set. For which LinkedHashSet and CopyOnWriteArraySet (thread-safe) can be used.

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?

只有 sortedSet 才能按 set 的顺序排序





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签