Replacing a HashSet Java member

前端 未结 5 1447
我在风中等你
我在风中等你 2021-01-07 16:47

I have Set of that structure. I do not have duplicates but when I call: set.add(element) -> and there is already exact element I would like the old to be replac

5条回答
  •  时光说笑
    2021-01-07 17:26

    Check the HashSet code within the JDK. When an element is added and is a duplicate, the old value is replaced. Folk think that the new element is discarded, it's wrong. So, you need no additional code in your case.

    UPDATED---------------------

    I re-read the code in JDK, and admit a mistake that I've made.

    When put is made, the VALUE is replaced not the KEY from an HashMap.

    Why am I talking about Hashmap??!! Because if you look at the HashSet code, you will notice:

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    

    So the PRESENT value is replaced with the new one as shown in this portion of code:

          public V put(K key, V value) {
            if (key == null)
                return putForNullKey(value);
            int hash = hash(key);
            int i = indexFor(hash, table.length);
            for (Entry e = table[i]; e != null; e = e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
            }
    
            modCount++;
            addEntry(hash, key, value, i);
            return null;
        }
    

    But I agree, the key isn't replaced, and since the keys represent the HashSet's values, this one is said to be "untouched".

提交回复
热议问题