本文共 1595 字,大约阅读时间需要 5 分钟。
for (int i = 0; i < selectedList.size(); i++) { if (!buildFunctionList.contains(selectedList.get(i).getType())) { selectedList.remove(i); } }
selectedList.remove(i);
显示有异常信息:
Reports when list.remove(index) is called inside the ascending counted loop. This is suspicious as list becomes shorter after that and the element next to removed will not be processed. Simple fix is to decrease the index variable after removal, but probably removing via iterator or using removeIf method (since Java 8) is a more robust alternative. If you don’t expect that remove will be called more than once in a loop, consider adding a break command after it.
查看方法:
/** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws UnsupportedOperationException if the remove operation * is not supported by this list * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= size()) */ E remove(int index);
发现:每移除一位,后面的index就会前进一位。
所以,可以这么写:
for (int i = 0; i < selectedList.size(); i++) { if (!buildFunctionList.contains(selectedList.get(i).getType())) { selectedList.remove(i); i--; } }
其余解决方式:
Iterator 、 逆遍历转载地址:http://yovcz.baihongyu.com/