list列表移除元素(list.remove())
list.remove()
/**
* Removes the element at the specified position in this list (optionaloperation).
* 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 <tt>remove</tt> operation
* is not supported by this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E remove(int Index);
案例1:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
for (int i = 0; i < list.size(); i++) {
if ("3".equals(list.get(i))) {
System.out.println(list.remove(i));//3
}
}
System.out.println(list);//[1, 2, 4]
案例2:
List<String> a = new ArrayList<>();
a.add("2");
a.add("2");
a.add("3");
a.add("3");
a.add("3");
a.add("3");
a.add("3");
a.add("4");
for (int i = 0; i < a.size(); i++) {
if("3".equals(a.get(i))){
System.out.println(i+"-"+a.remove(i));
}
}
System.out.println(a);
输出结果:
2-3
3-3
4-3
[2, 2, 3, 3, 4]
分析:
很明显,结果不是想要的。当i=2时,a.get(i)==3,然后移除;后面的四个元素的索引会向左移,也就是原本下标为3的值
放在了下标为2的位置;当i++后,下次移除的是i=3的元素,但此时i=2对应的值是3,并没有删除;以此类推结果为[2,2,3,3]。
想输出[2,2,4]请看案例3
案例3:
List<String> a = new ArrayList<>();
a.add("2");
a.add("2");
a.add("3");
a.add("3");
a.add("3");
a.add("3");
a.add("3");
a.add("4");
for (int i = 0; i < a.size(); i++) {
if("3".equals(a.get(i))){
System.out.println(i+"-"+a.remove(i));
i--;
}
}
System.out.println(a);
输出结果:
2-3
2-3
2-3
2-3
2-3
[2, 2, 4]
分析:
在案例2的基础上,加上"i--"语句,因为之前分析过移除元素后,后面元素的下标会左移,i--能解决这个问题。