ArrayList中的remove方法的坑
public E remove(int index);
public boolean remove(Object o);
这是ArrayList中remove的两个重载方法
传入的index为基本数据类型则是按下标进行删除
传入的index为包装类型则是按值进行删除,内部是通过equals方法进行比较。
public static void main(String[] args) {
removeByIndex(2);
removeByValue(2);
}
private static void removeByIndex(int index) {
List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
list.remove(index);
System.out.println("removeByIndex:" + list);
}
private static void removeByValue(Integer index) {
List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
list.remove(index);
System.out.println("removeByValue:" + list);
}
输出结果如下:
removeByIndex:[1, 2, 4, 5, 6, 7, 8, 9, 10]
removeByValue:[1, 3, 4, 5, 6, 7, 8, 9, 10]