第一个索引设置为null(空),但它不打印正确的输出,为什么?
//set the first index as null and the rest as "High"
String a []= {null,"High","High","High","High","High"};
//add array to arraylist
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a));
for(int i=0; i<choice.size(); i++){
if(i==0){
if(choice.get(0).equals(null))
System.out.println("I am empty"); //it doesn't print this output
}
}
答案 0 :(得分:6)
我相信你想做的就是改变,
if(choice.get(0).equals(null))
到
if(choice.get(0) == null))
答案 1 :(得分:6)
你想:
for (int i=0; i<choice.size(); i++) {
if (i==0) {
if (choice.get(0) == null) {
System.out.println("I am empty"); //it doesn't print this output
}
}
}
表达式choice.get(0).equals(null)
应抛出NullPointerException
,因为choice.get(0)
为null
,您尝试在其上调用函数。因此,anyObject.equals(null)
将始终返回false
。