为什么HashSet保持自然/字母顺序? [英] Why is HashSet maintaining natural/ alphabetical order?

查看:129
本文介绍了为什么HashSet保持自然/字母顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的代码时,它总是以自然/字母顺序给出o/p.据我所知,HashSet不会对条目进行排序.我知道HashSetHashMap而不是LinkedHashMap支持.我尝试浏览HashSetHashMap的源代码,但找不到此行为的代码.

When I run below code it is always giving the o/p in natural/ alphabetical order. As per I know HashSet doesn't sort the entries. I know that HashSet is backed by HashMap and not LinkedHashMap. I tried to explore the source code of HashSet and HashMap but couldn't find the code for this behavior.

在源代码中,HashSet类中的构造函数如下:

From the source code there is below constructor in HashSet class:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

使用LinkedHashMap

.如果我使用了此构造函数,我会认为这是造成这种现象的原因,但我没有使用此构造函数.

which uses LinkedHashMap. If I had used this constructor I would think this is the reason for this behavior but I'm not using this constructor.

有人可以解释此行为的原因/代码吗?

Could someone please explain the reason/ code for this behavior?

这是我的简单代码:

Set<String> mySet = new HashSet<>();

        mySet.add("D");
        mySet.add("B");
        mySet.add("1");
        mySet.add("E");
        mySet.add("A");
        mySet.add("F");

        mySet.stream().forEach(x -> System.out.println(x));

OP:

OP:

1
A
B
D
E
F

推荐答案

这是巧合,因为默认的HashSet大于哈希的范围,并且没有冲突,并且字符串的哈希最终以字母顺序排列

This is coincidence because the default HashSet is bigger than the range of the hashes and there are no collisions, and the hashes for the Strings end up being in alphabetical order.

这是String.hashCode的代码:

This is the code for String.hashCode:

   public int hashCode() {
        int h = hash;
        if (h == 0) {
            int off = offset;
            char val[] = value;
            int len = count;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

如您所见,一个字符字符串的哈希最终只是字符值.

As you can see, the hash for one-character string ends up just being the character value.

默认容量为16,这意味着您的所有值最终都在存储区char value % 16中,对于您的示例,该存储区按字母顺序排序.尝试使用"2"而不是"1",例如,应以"A"结尾.即使您交换"A"和"1",这也应在输出中交换它们.参见 Ascii表.

The default capacity of HashSet is 16, which means all your values end up in the bucket char value % 16 which turns out to be alphabetical order for your example. Try with "2" instead of "1", for example, this should end up after "A". Even if you swap "A" and "1" this should swap them in the output too. See Ascii table.

这篇关于为什么HashSet保持自然/字母顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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