Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Value of put() in HashMap

I was having trouble understanding the explanation for return value of put() in a HashMap:

  private Map<Bookmark, Integer> mDevice = new HashMap<String, Integer>();

    String abc = "two"
    Integer ret = mDevice.put(abc, ONLINE);

Am I correct in saying the following:

  1. if abc key already exists with value OFFLINE, ret is equal to OFFLINE.
  2. if abc key already exists with value ONLINE, ret is equal to ONLINE.
  3. if abc key did not exist, then ret is equal to null.
like image 650
Sunny Avatar asked Apr 12 '13 10:04

Sunny


People also ask

What is the return type of map put method in HashMap?

put(key,value) is return type of 'value' in hashmap.

What is the return value of put?

Return Value The puts() function returns EOF if an error occurs. A nonnegative return value indicates that no error has occurred.

What does put method return in Java?

HashMap put() Method in Java put method returns the previous value associated with the specified key if there was mapping for the specified key else it returns null. Syntax. Object put(K key, V value) Parameters key - key for the entry, value - value to be associated with the key.


1 Answers

The method put has a return type same with the value:

    @Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }

The method 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.

It returns the previous value associated with key, or null if there was no mapping for key.So, your points are right.

For more details please visit here

like image 139
Shreyos Adikari Avatar answered Oct 03 '22 19:10

Shreyos Adikari