Java HashMap map.put("key", null); 与 map.remove("key"); 的区别
用 getOrDefault,Map 中原来 value 为 null 的部分不会使用 defaultValue 而是直接返回 null
问题记录时间:2023.10.10
整理博客时间:2024.01.13
Java 对于Map的处理
import java.util.HashMap;
public class CodeTest {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
map.put("anotherKey", "anotherValue");
System.out.println(map); // {anotherKey=anotherValue, key=value}
map.remove("key");
map.put("anotherKey", null);
System.out.println(map); // {anotherKey=null}
System.out.println(map.getOrDefault("key", "key: defaultValue")); // key: defaultValue
System.out.println(map.getOrDefault("anotherKey", "anotherKey: defaultValue")); // null
map.replace("foo1", "bar1"); // 有这个 key 才替换
map.put("foo2", "bar2"); // 不管原来有没有这个 key 直接插入
System.out.println(map); // {anotherKey=null, foo2=bar2}
}
}JavaScript 对于字典的处理
let map = {
key:"value",
anotherKey:"anotherValue",
foo: "bar",
};
delete map.key;
map.anotherKey = undefined;
map.foo = null;
console.log(map);
// {anotherKey: undefined, foo: null}
console.log(JSON.stringify(map));
// {"foo":null}本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work
尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。
GitHub登录