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

查看:89
本文介绍了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天全站免登陆