我有一个对象数组。我想扫描它,只要我找到的对象不为空,就将计数器加 1。当我找到第一个空对象时,我想跳出 for 循环,因为没有理由继续循环。
我写了以下代码:
// counter variable initialized to zero
int counter = 0;
// scan the array
for(int i = 0; i < this.array.length; i++) {
// as long as the object found is not null
while(!this.array[i].equals(null)) {
// increase the value of the counter by 1
counter += 1;
}
// when the first null object found, jump out of the loop
break;
}
for循环中的i++被标记,警告为Dead Code。但是,我想这是有道理的,因为当我找到第一个空对象时,我会停止循环。所以没什么好担心的,或者......?