一、在Java中List.remove方法有个bug
1.看第一个针对Object的
boolean remove(Object var1);
看一下API接口,在看一下实现类
实现类:
/**
* {@inheritDoc}
*
* <p>This implementation iterates over the collection looking for the
* specified element. If it finds the element, it removes the element
* from the collection using the iterator's remove method.
*
* <p>Note that this implementation throws an
* <tt>UnsupportedOperationException</tt> if the iterator returned by this
* collection's iterator method does not implement the <tt>remove</tt>
* method and this collection contains the specified object.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
2.看第二个针对索引
E remove(int var1);
看一下实现类
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
throw new UnsupportedOperationException();
}
二、在实际工作中可能会出现的bug
看一下代码
package net.println.kotlin.chapter4;
import java.util.ArrayList;
import java.util.List;
/**
* @author:wangdong
* @description:看一下list的bug
*/
public class Bug {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>();
integerList.add(23);
integerList.add(233);
integerList.add(243);
integerList.add(235);
integerList.add(5);
integerList.add(50);
integerList.add(500);
System.out.println(integerList);
//这里会出现一个bug,当list中存在与索引相同的元素的时候,使用remove,就不知道会删除掉那个了
integerList.remove(1);
//这个5的索引是4,这样写可能就删除了索引为5的50,也可能是删除了5的元素
integerList.remove(5);
System.out.println(integerList);
}
}