Java中HashSet是乱序的吗?

 结论:HashSet跟添加元素顺序无关,但是内部有固定顺序,是按hash顺序存储。

package com.example.demo.java;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class HashSetDemo {
    @Test
    public void hashSetDemo(){
        Set hashSet = new HashSet();
        hashSet.add(1);
        hashSet.add(3);
        hashSet.add(2);
        hashSet.add("c");
        hashSet.add("b");
        hashSet.add("a");
        hashSet.add("d");
        log.info(hashSet.toString());
       for (Object it:hashSet){
           log.info(it.toString());
       }

    }
}

输出顺序是固定的:

23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - [1, a, 2, b, 3, c, d]
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 1
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - a
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 2
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - b
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 3
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - c
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - d

 如果你希望乱序输出,恐怕要让你失望了。无论怎么修改添加元素的顺序。都只有上面一种输出顺序。

 

源码:

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

创建一个HashSet实际上是创建了HashMap。

    /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

添加一个元素的时候,把元素当key,new Object为value。添加到map中这样保证了Set的值唯一的特性。

接下来就是HashMap那一套了。添加元素源码如下:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //1.如果key相等,且hash值相等,则替换掉
                e = p;
            else if (p instanceof TreeNode)
                //2.1如果 p是TreeNode的实例。表示是红黑树,直接插入红黑树中
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//2.2 不是TreeNode,表示是链表,则放在链表的最末端
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //当链表长度达到8时,改为红黑树结构
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

HashMap中元素的存储有可能有两种形式,红黑树或者链表,当链表大小达到8时,转为红黑树存储。

两种数据结构添加节点的关键方法:

链表:p.next = newNode(hash, key, value, null);
红黑树:e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞翔的咩咩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值