【问题标题】:Why doesn't list.get(0).equals(null) work?为什么 list.get(0).equals(null) 不起作用?
【发布时间】:2010-03-31 22:39:54
【问题描述】:

第一个索引设置为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
    }
}

【问题讨论】:

  • 小窍门:System.out.println(Arrays.asList(null,"High","High","High","High","High")); 无需所有额外代码即可满足您的需求。我说它是“相同的”,因为你可能不知道你可以打印空值

标签: java list null arraylist


【解决方案1】:

我相信你想做的就是改变,

if(choice.get(0).equals(null))

if(choice.get(0) == null))

【讨论】:

  • 没问题,请参阅 cletus 的回答,了解为什么它没有按预期工作的更深入的原因。
【解决方案2】:

你想要:

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

【讨论】:

  • 虽然为 equals(null) 返回 true 违反了 API 约定,但实际上很有可能。
猜你喜欢
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多