list列表移除元素(list.remove())

list列表移除元素(list.remove())

list.remove()

案例1:

案例2:

案例3:


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 &lt; 0 || index &gt;= 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--能解决这个问题。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值