Java ArrayList 移除元素:remove(int index) 和 removeAll(Collection c)
ArrayList 类是 Java 中的一个动态数组类,提供了丰富的操作方法,其中包括 remove(int index) 方法和 removeAll(Collection c) 方法,用于移除列表中的元素。
- remove(int index) 方法用于从列表中删除指定索引位置的元素,并返回被删除的元素。
ArrayList<String> list = new ArrayList<>();
list.add('A');
list.add('B');
list.add('C');
String removedElement = list.remove(1);
System.out.println('被删除的元素是:' + removedElement);
System.out.println('列表剩余元素:' + list);
输出结果:
被删除的元素是:B
列表剩余元素:[A, C]
- removeAll(Collection c) 方法用于从列表中移除指定集合 c 中的所有元素。
ArrayList<String> list1 = new ArrayList<>();
list1.add('A');
list1.add('B');
list1.add('C');
ArrayList<String> list2 = new ArrayList<>();
list2.add('B');
list2.add('C');
boolean removedAll = list1.removeAll(list2);
System.out.println('是否成功移除所有元素:' + removedAll);
System.out.println('列表剩余元素:' + list1);
输出结果:
是否成功移除所有元素:true
列表剩余元素:[A]
注意:removeAll 方法返回一个 boolean 值,表示是否成功移除了所有元素。
原文地址: https://www.cveoy.top/t/topic/p2Ob 著作权归作者所有。请勿转载和采集!