put(k,v)
源代码:(jdk1.8.0)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
如果插入的数据不存在,插入成功,返回null
如果插入的数据存在,返回原有的数据,并用新的value,更新旧的value。
实践操作:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> mapObj = new HashMap<>();
System.out.println(mapObj.put(1,"first"));// 输出:null
System.out.println(mapObj.put(1,"first")); // 输出: first ,两次插入一样的数据,
System.out.printf("mapObj的数据: %s \n",mapObj); // mapObj的数据: {1=first}
System.out.println(mapObj.put(1,"first222")); // 输出: first , 插入不一样的数据
System.out.printf("mapObj的数据: %s \n",mapObj); // mapObj的数据: {1=first222}
}
}
putIfAbsent()
源代码:(jdk 1.8.0)
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
如果插入的数据不存在,插入成功,返回null
如果插入的数据存在,返回原有的数据
实践操作:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> mapObj = new HashMap<>();
System.out.println(mapObj.putIfAbsent(1,"first")); // null
System.out.println(mapObj.putIfAbsent(1,"first111")); // first
System.out.printf("mapObj的数据: %s \n",mapObj); // mapObj的数据: {1=first222}
}
}
putIfAbsent和put的区别
插入存在的数据时,是否会用新value替换旧value。
put会,putIfAbsent不会。
putAll()
源码:(jdk 1.8.0)
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
实践操作:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer,String> mapObj = new HashMap<>();
mapObj.put(1,"first");
System.out.printf("mapObj的数据: %s \n",mapObj); // mapObj的数据: {1=first222}
HashMap<Integer,String> mapObj2 = new HashMap<>();
mapObj2.put(2,"second");
mapObj2.put(3,"three");
System.out.printf("mapObj2的数据:%s \n",mapObj2); // mapObj2的数据:{2=second, 3=three}
mapObj.putAll(mapObj2); // 将mapobj2 添加到mapobj中
System.out.printf("mapObj2添加到mapObj后,mapObj的数据为:%s \n", mapObj);
// mapObj2添加到mapObj后,mapObj的数据为:{1=first, 2=second, 3=three}
mapObj.put(3,"three33");
System.out.printf("更新后的mapObj:%s \n",mapObj);
System.out.printf("判断mapObj2是否变更:%s \n",mapObj2); //应该是不会变的,说明putAll传的是value,不是地址
/*
* 更新后的mapObj:{1=first, 2=second, 3=three33}
* 判断mapObj2是否变更:{2=second, 3=three}
* */
// putAll 添加已经存在的数据,会怎样??
HashMap<Integer,String> mapObj3 = new HashMap<>();
mapObj3.put(2,"second");
mapObj3.put(4,"four");
mapObj.putAll(mapObj3);
System.out.printf("mapObj3添加到mapObj后,mapObj的数据为:%s \n", mapObj);
// mapObj3添加到mapObj后,mapObj的数据为:{1=first, 2=second, 3=three33, 4=four}
}
}