Java HashSet 以奇怪的顺序显示列表,总是从 3 开始 [英] Java HashSet shows list in weird order, always starting with 3

查看:23
本文介绍了Java HashSet 以奇怪的顺序显示列表,总是从 3 开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,它实际上只是来自文件的整数列表.我将其转换为 HashSet 以删除重复项,如下所示:

I have array of Strings which actually in nothing but list of integers coming from file. I converted it to HashSet so as to remove duplicates as follows:

Set<String> intSet = new HashSet<String>(Arrays.asList(strArr));

我希望所有数字都按顺序排列,但当然,因为这是一个字符串而不是整数列表,所以它可能没有按顺序排列.但是每当我尝试打印这个 HashSet 时,我总是得到如下输出:

I expected that it all the numbers to be in order but off course, since this is a string and not integer list, it may not come in order. But whenever I try to print this HashSet, I always get output as follows:

[3, 2, 1, 4]
[3, 2, 5, 4]

每次,如果 3 出现,它就被认为是第一个元素.我不明白为什么它会这样?谁能给我解释一下.

Every time, if 3 is present it is considered to be first element. I am not getting why it is acting this way? Can anyone please explain me this.

推荐答案

返回顺序取决于内部散列算法,您应该对此无动于衷.(散列算法背后的想法是将键值均匀地分散到一个内部表中.由于该算法可能是确定性的,因此您每次可能会得到 3 个).

The order of return is dependent on an internal hashing algorithm, to which you are supposed to be indifferent. (The idea behind the hashing algorithm is to disperse key values uniformly across an internal table. You probably get 3 back every time since this algorithm is probably deterministic).

如果您想按字典顺序返回内容,请使用 TreeSet.

If you want things back in lexographic order then use a TreeSet.

要保留插入顺序,请使用 LinkedHashSet.

To preserve the order of insertion, use a LinkedHashSet.

这篇关于Java HashSet 以奇怪的顺序显示列表,总是从 3 开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆