HashMap解析——HashMap的put方法返回值

首先,看一下源码:

 

 

public V put(K paramK, V paramV)
  {
    if (paramK == null) {
      return putForNullKey(paramV);
    }
    int i = hash(paramK.hashCode());
    int j = indexFor(i, this.table.length);
    for (Entry localEntry = this.table[j]; localEntry != null; localEntry = localEntry.next)
    {
      Object localObject1;
      if ((localEntry.hash == i) && (((localObject1 = localEntry.key) == paramK) || (paramK.equals(localObject1))))
      {
        Object localObject2 = localEntry.value;
        localEntry.value = paramV;
        localEntry.recordAccess(this);
        return localObject2;
      }
    }
    this.modCount += 1;
    addEntry(i, paramK, paramV, j);
    return null;
  }

好吧,看不懂没关系,下面看例子:

 

 

import java.util.HashMap;
import java.util.Map;


public class Test {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		String p1 = map.put("11", "22");
		System.out.println("p1:" + p1);

		String p2 = map.put("33", "44");
		System.out.println("p2:" + p2);

		String value1 = map.get("11");
		System.out.println("value1:" + value1);

		String p3 = map.put("11", "44");
		System.out.println("p3:" + p3);

		String value2 = map.get("11");
		System.out.println("value2:" + value2);
	}
}

输出结果:

 

 

p1:null
p2:null
value1:22
p3:22
value2:44

说明:put方法返回值为null或者value;

 

如果key没有重复,put成功,则返回null,如p1、p2;

如果key重复了,返回的是map.get(key),也就是当前这个key对应的value,如上面的p3,key=”11″,而p1的key也是”11″,p1与p3重复,返回的是p1的value=”22″,并且将p3覆盖掉p1

 

 

 

 

    原文作者:冷静cc
    原文地址: https://blog.csdn.net/love_java_cc/article/details/56674401
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞