List.remove 方法的基本原理
List.remove 方法是 Java 集合框架中常用的操作之一,用于从列表中移除指定元素或指定索引位置的元素。它的行为取决于参数类型:如果传入的是对象,则移除第一个匹配的元素;如果传入的是索引,则移除该位置的元素。以下是两种重载方法的签名:
boolean remove(Object o);
E remove(int index);
对于对象类型的移除,方法会遍历列表,找到第一个与给定对象相等的元素并移除。对于索引移除,方法会直接访问指定位置的元素并删除,同时后续元素会向前移动填补空缺。
使用 List.remove 移除对象
当使用 remove(Object o) 方法时,列表会通过 equals 方法比较元素是否匹配。如果找到匹配项,移除后返回 true;否则返回 false。以下是一个示例:
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
boolean isRemoved = fruits.remove("Banana");
System.out.println(isRemoved); // 输出 true
System.out.println(fruits); // 输出 [Apple, Orange]
需要注意的是,如果列表中存在多个相同的元素,remove 方法只会移除第一个匹配项。例如:
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(2);
numbers.add(3);
numbers.remove(Integer.valueOf(2));
System.out.println(numbers); // 输出 [1, 2, 3]
使用 List.remove 移除索引
当使用 remove(int index) 方法时,列表会移除指定位置的元素并返回被移除的元素。索引必须是有效的(即 0 <= index < size()),否则会抛出 IndexOutOfBoundsException。示例:
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
String removedColor = colors.remove(1);
System.out.println(removedColor); // 输出 Green
System.out.println(colors); // 输出 [Red, Blue]
1259

被折叠的 条评论
为什么被折叠?



