我正在练习几周后的编程考试。其中较小的任务之一是请求用户输入(链接)并将其添加到唯一列表(集)中。
这就是我的做法(并且有效):
DefaulListModel m = new DefaulListModel();
JList aList = new JList(m);
ArrayList<String> lenker = new ArrayList<String>();
Set<String> unique;
(...)
String url = JOptionPane.showInputDialog(null, "Skriv inn URL");
lenker.add(url);
unique = new HashSet<String>(lenker);
this.oppdaterGUI(liste, unique);
(...)
public void oppdaterGUI(JList liste, Set<String> array){
m.clear();
for(Object s : array){
m.addElement((String) s);
aList.setModel(m)
}
这是我的问题:当我测试它时,我输入了数字 1,2,3,4,5,1
现在我假设 ArrayList 包含数字 [1,5,4,3,2,1] 我假设将其添加到 HashSet 后,它应该看起来像 {5,4,3,2,1}
但是,它看起来像这样:{3,2,1,5,4}
为什么我的假设是错误的?
编辑:澄清。我知道 HashSet 没有排序(即 TreeSet),但是当我添加数字时,它们已经排序了,为什么它们没有排序?我已经这样做过很多次了,每次它们出来时都没有分类,而且方式完全相同。每次。
最佳答案
So why are my assumptions wrong? I am just curious. It might be because my code sucks, I don't know, that's why I am asking here.
集合不是排序的数据结构。没有更多了:)
但是,Set 实现具有排序机制。例如,treeset .
<小时/>回答您的编辑:
它们未排序,因为 HashSet 内部使用 HashMap,它通过某种哈希算法将条目分布在存储桶中。这些存储桶按某种顺序进行检查,但不能保证保持不变。
关于java - HashSet是如何排序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140189/