Java开发:合并ArrayList时遭遇NullPointerException问题排查
解决JSF项目中合并ArrayList时的NullPointerException问题
咱们直接说根源:当chips组件为空时,你的arrayList2是null,但代码里直接调用了arrayList2.size(),这就触发了NullPointerException。
问题细节拆解
你当前代码的几个致命问题:
- 集合初始化不严谨:只有调用
arrayList2List()时才会给arrayList2创建实例,但如果用户没操作chips组件,这个方法可能根本没被触发,导致arrayList2一直是null。 - 空指针触发点:
- 代码开头
int lengthlist2 = arrayList2.size();,如果arrayList2是null,这里直接抛出空指针异常。 - 第二个分支
else if (lengthlist1 > 0 && arrayList2.size() == 0),同样,当arrayList2为null时,调用size()方法必炸。
- 代码开头
修复方案
核心思路是先把null集合转换成空集合,再进行后续判断,同时从根源上优化集合的初始化逻辑。
第一步:提前兜底null集合
在concatenate()方法开头,先处理可能为null的集合,避免后续调用方法时抛异常:
// 把null转换成空集合,确保后续调用size()、遍历等操作安全 if (arrayList1 == null) { arrayList1 = new ArrayList<>(); } if (arrayList2 == null) { arrayList2 = new ArrayList<>(); }
第二步:优化分支判断与代码可读性
现在两个集合都不会是null了,可以安全调用size(),同时用增强for循环简化遍历逻辑:
public void concatenate() throws IOException { // 先处理null集合,兜底为空集合 if (arrayList1 == null) { arrayList1 = new ArrayList<>(); } if (arrayList2 == null) { arrayList2 = new ArrayList<>(); } int lengthlist1 = arrayList1.size(); int lengthlist2 = arrayList2.size(); ArrayList<String> concat = new ArrayList<>(); if (lengthlist1 > 0 && lengthlist2 > 0) { // 两个集合都有内容的逻辑 for (String item1 : arrayList1) { concat.add(item1 + And + wordx); for (String item2 : arrayList2) { concat.add(item2 + And + wordx); } } } else if (lengthlist1 > 0) { // 只有arrayList1有内容的逻辑 for (String item1 : arrayList1) { concat.add(item1 + And + wordx); } } else if (lengthlist2 > 0) { // 只有arrayList2有内容的逻辑 for (String item2 : arrayList2) { concat.add(item2 + And + wordx); } } else { // 两个集合都为空的逻辑 // TODO: do something else } // 遍历执行搜索 for (String keyword : concat) { Search(keyword); } }
额外建议:从根源避免null
可以在声明集合时直接初始化,彻底避免null的出现:
private List<String> arrayList1 = new ArrayList<>(); private List<String> arrayList2 = new ArrayList<>();
这样即使用户没操作复选框或chips组件,集合也是空的而非null,从源头减少空指针异常的可能。
内容的提问来源于stack exchange,提问作者KontrCode
相关产品推荐
相关产品推荐

