简体   繁体   中英

HashMap put method

I'm having some trouble when using .put(Integer, String) in Java. To my understanding, when a collision happens the HashMap asks whether the to value are the same with .equals(Object) and if they are not the two values are stored in a LinkedList . Nevertheless, size() is 1 and the hash iterator only shows one result, the last one.

Apart form this, java HashMap API states:put

 public V put(K key, V value) 

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

THIS IS NOT WHAT I HAVE READ EVERYWHERE.

Thoughts?

public class HashProblema {

    public static void main(String[] args) {
        HashMap<Integer, String> hash= new HashMap();
        hash.put(1, "sdaaaar");
        hash.put(1, "bjbh");

        System.out.println(hash.size());
        for (Object value : hash.values()) {
            System.out.println(value);
        }
    }
}

The output is -:

1
bjbh

Since the mapping for the key exist, it is replaced and the size remains 1 only.

值被新键覆盖。大小保持不变,并且值被更改。这就是它的工作原理,因为键值始终是唯一的。您不能在一个键上映射多个值。

The API is the definitive reference and that is what you must believe.

A collision occurs when the hash of of a key already exists in the HashMap. Then the values of the keys are compared, and if they are the different, the entries are placed in a linked list. If the keys are the same, then the old key-value in the HashMap is overwritten.

API documentation should normally be treated as authoritative unless there is very good reason to doubt its accuracy.

You should almost certainly ignore any claim that doesn't flag itself as 'knowingly' at odds with documentation and provide a testable evidence.

I humbly suggest you might be confused about the role of a linked 'collision' list. As it happens HashMap in Java uses a linked-list to store multiple values for which the hash-code of the key is placed in the same 'bucket' as one or more other keys.

A HashMap in Java will always store a Key-Value-Pair. There are no linked lists involved. What you are describing is the general idea of a hash map (often taught in computer science class), but the implementation in Java is different. Here, you will always have one value per key only (the last one you put in that place).

However, you are free to define a HashMap that contains List objects. Though, you have to keep track of duplicates and collisions on your own then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM