DESKTOP-TEACTL5_20200908-曾越

问题:

在实现Collection重写retainAll方法时,将调用remove方法的条件设置错误,导致最后集合中没有任何元素而发生空指针异常。

@Override
public boolean retainAll(Collection<?> c) {
// if(c instanceof Box) {
// Box other=(Box)c;
// Object[] otherArray=other.array;
// for(int i=0;i<count;i++) {
// for(int j=0;j<other.count;j++) {
// if(!(array[i].equals(otherArray[j]))) {
// remove(array[i]);
// }
// }
// }
// }
if(c instanceof Box) {
Box other=(Box)c;
Object[] otherArray=other.array;
for(int i=0;i<other.count;i++) {
if(!contains(otherArray[i])) {
remove(otherArray[i]);
}
}
}
return true;
}

总结:

在以下for循环中会将集合中所有元素移除从而导致空指针异常。

for(int j=0;j<other.count;j++) {
if(!(array[i].equals(otherArray[j]))) {
remove(array[i]);
}
}