0

I wondering that a Hashmap handle the value once the Key is same. I insert 2 element with same key using put method. if there is no value exist it return null otherwise it return the privous value shored. does hashMap does not store multiple value for same Key

public class geekarray {
    HashMap<Integer, String> a ;
    geekarray(){
        a= new HashMap<Integer,String>(10);

        System.out.println(a.put(1, "yogi"));
        System.out.println(a.put(1, "yogi2"));
        System.out.println(a.put(2, "yogi3"));
    }
    public static void main(String s[]){
        geekarray a = new geekarray();

    }
}

Output:-

null
yogi
null
jmj
  • 237,923
  • 42
  • 401
  • 438
dead programmer
  • 4,223
  • 9
  • 46
  • 77

4 Answers4

1

No. A HashMap only stores one value per key (which is unique) the old value is overwritten with the new one. You could look at Apache Common Utils MultiMap if you are interested in storing multiple values per key.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

It does not store multiple values for the same key. The new value replaces the old 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.

(Source)

As for the return value :

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Eran
  • 387,369
  • 54
  • 702
  • 768
0

No, HashMap does not store multiple values for the same key. And as the documentation says,

If the map previously contained a mapping for the key, the old value is replaced. 
Swapnil
  • 8,201
  • 4
  • 38
  • 57
0

According to the Java 7 documentation:

If the map previously contained a mapping for the key, the old value is replaced.

So you can only put one value per key. Any additional puts will overwrite the existing value.

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put(K,%20V)

Akshay
  • 814
  • 6
  • 19