如何在java中限制哈希集的默認排序 (how to restrict default ordering of Hash Set in java)


問題描述

如何在java中限制哈希集的默認排序 (how to restrict default ordering of Hash Set in java)

I have some of values in my java program. I just stored those values in HashSet. I have stored it by for loop. The values iterating by loop has been ordered differently after the set formed. How can restrict this order change of HashSet as I get from the loop. Can anyone help me please?

‑‑‑‑‑

參考解法

方法 1:

If you want the set to maintain the insertion order, you can use a LinkedHashSet:

  

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)

Alternatively, if you want your set to be ordered, you can use a TreeSet.

方法 2:

HashSet is unordered, as the javadocs specify:

  

It makes no guarantees as to the iteration order of the set; in   particular, it does not guarantee that the order will remain constant   over time. This class permits the null element.

You might want to consider using a LinkedHashSet, which maintains the order of insertions.

An alternative is using one of the NavigableSet implementations, such as the TreeSet which guarantee order according to the natural order or Comparator, if given.

方法 3:

use LinkedHashSet predictable iteration order

(by Sangeetha KrishnanassyliasamitAnton Arhipov)

參考文件

  1. how to restrict default ordering of Hash Set in java (CC BY‑SA 3.0/4.0)

#java #collections #set






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論