使用Arrays.asList创建的列表整合到新List时触发NullPointerException问题
空指针异常原因分析与解决方法
异常原因
你仅声明了List<Europe> europeList;但未对该列表进行初始化,此时europeList的引用为null。当你在循环中调用europeList.add()方法时,对null对象调用方法就会触发NullPointerException。
解决方法
方法1:初始化列表后再添加元素
在声明列表时,直接用具体的实现类(比如ArrayList)完成初始化,示例代码如下:
// 初始化列表,使用ArrayList作为实现类 List<Europe> europeList = new ArrayList<>(); for (int i=0; i<countriesEurope.size(); i++){ europeList.add(new Europe(countriesEurope.get(i), populationEurope.get(i), surfaceEurope.get(i))); }
方法2:使用Java 8+ Stream API简化实现
可以通过IntStream遍历索引,将三个列表的对应元素映射为Europe对象,最后收集为列表,避免手动循环:
List<Europe> europeList = IntStream.range(0, countriesEurope.size()) .mapToObj(i -> new Europe( countriesEurope.get(i), populationEurope.get(i), surfaceEurope.get(i) )) .collect(Collectors.toList());
注意:使用该方式需要导入java.util.stream.IntStream和java.util.stream.Collectors包。
内容的提问来源于stack exchange,提问作者theadvocate
相关产品推荐
相关产品推荐

