Map 下的 NPE

http://www.cnblogs.com/mafly/p/trap.html

Map 下的 NPE
1.Map 类集合 K/V 能不能存储 null 值的情况,如下表格:

集合类 Key Value Super 说明
Hashtable 不允许为 null 不允许为 null Dictionary 线程安全
ConcurrentHashMap 不允许为 null 不允许为 null AbstractMap 分段锁技术
TreeMap 不允许为 null 允许为 null AbstractMap 线程不安全
HashMap 允许为 null 允许为 null AbstractMap 线程不安全

2.foreach 遍历集合删除元素

public static void main(String[] args) {
    List<String> a = new ArrayList<>();
    a.add("1");
    a.add("2");
    a.add("3");

    for (String temp : a) {
        if ("2".equals(temp)) {
            a.remove(temp);
        }
    }

    Iterator<String> it = a.iterator();
    while (it.hasNext()) {
        String temp = it.next();
        if ("2".equals(temp)) {
            it.remove();
        }
    }
}

不要在 foreach 循环里进行元素的 remove/add 操作。remove 元素请使用 Iterator 方式(代码第二种),如果并发操作,需要对 Iterator 对象加锁。

3.Arrays.asList() 数组转换集合

 public static void main(String[] args) {
        String[] str = new String[]{"a","b"}; 
        List list = Arrays.asList(str);
        list.add("c");//报错
        
//        str[0] = "d";
        for(Object o : list){
            System.out.println(o);
        }
}

踩坑姿势: Arrays.asList()把数组转换成集合时,不能使用其修改集合相关的方法,它的 add/remove/clear 方法会抛出 UnsupportedOperationException 异常。 asList() 的返回对象是一个 Arrays 内部类,并没有实现集合的修改方法。
解决方案: 在转换之前操作咯。还需要注意一点,在你转换后,再对数组的值进行修改时,集合也会跟着变哦(注释掉的代码)。

4.toArray() 集合转换数组

package com.example.demo;

import java.util.ArrayList;
import java.util.List;

public class ListToArray {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("你好");
        list.add("傻瓜");
        String[] objects = (String[]) list.toArray();
        System.out.println(objects);
    }
}

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
	at com.example.demo.ListToArray.main(ListToArray.java:11)

会报 ClassCastException 异常。
踩坑姿势: 直接使用 toArray() 无参方法返回值只能是 Object[]类,若强转其它类型数组将会抛异常。
解决方案: 使用 T[] toArray(T[] a); 有参数这个方法,代码如下:

package com.example.demo;

import java.util.ArrayList;
import java.util.List;

public class ListToArray {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("你好");
        list.add("傻瓜");
        String[] array = new String[list.size()];
        array = list.toArray(array);
        System.out.println(array);
    }
}

猜你喜欢

转载自blog.csdn.net/qyj19920704/article/details/83834013