gpt4 book ai didi

java - 如何避免空指针错误

转载 作者:行者123 更新时间:2023-12-01 06:27:49 26 4
gpt4 key购买 nike

我试图找出 2 个 arrayList 的元素是否匹配。但这段代码给了我错误 Exception in thread "AWT-EventQueue-0"java.lang.NullPointerException 因为某些元素为 null。

如何解决这个问题?

String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));

String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));

//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}

最佳答案

只需使用 Arrays.equals,如下所示:

    String level []={"High","High","High","High","High","High"};

String choice []={null,"High","Low","High",null,"Medium"};

return Arrays.equals(level, choice);

关于java - 如何避免空指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2561951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com