List中删除元素的6种方法比较--前两种就是坑,因为size指针前移。

这里占用点地方记录LIst接口的几个常用方法:
List接口:
void add(int index, E element)
boolean remove(Object o);
boolean contains(Object o)
E get(int index)
E set(int index, E element)
直接上代码

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.*;

@RunWith(SpringJUnit4ClassRunner.class)  //更改junit的运行期,不要直接去找junit,而是先找spring-test,test模块才能拿到容器
@ContextConfiguration("classpath:applicationContext.xml")  //告知spring的配置文件
public class CollectionTest {
    @Test
    public void testListRemove0(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方式0: 使用增强for
        try {
            for (String s : strings){
                if ("詹姆士".equals(s)){
                    strings.remove(s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(strings); //事实上会报ConcurrentModificationException异常
            // [科比, 韦德, 詹姆士, 詹姆士, 博士, 詹姆士]
        }
    }
    @Test
    public void testListRemove1(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方法1:
        try {
            Iterator<String> iterator = strings.iterator();
            while(iterator.hasNext()){
                String next = iterator.next();
                if ("詹姆士".equals(next)){ //才不会运行师报空指针异常
                    strings.remove(next);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(strings);  //事实上会出现ConcurrentModificationException:并发修改异常,
            // [科比, 韦德, 詹姆士, 詹姆士, 博士, 詹姆士] , 说明在remove第二个"詹姆士"的时候就会报这个concurrentmodificationException
        }
    }
    @Test
    public void testListRemove2(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方法2:使用迭代器删除
        Iterator<String> iterator = strings.iterator();
        while(iterator.hasNext()){
            String next = iterator.next();
            if ("詹姆士".equals(next)){
                iterator.remove();
            }
        }
        System.out.println(strings); //[科比, 韦德, 博士], 说明删除成功
    }
    @Test
    public void testListRemove3(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方法2:判断之后再删除
        while(strings.contains("詹姆士")){
            strings.remove("詹姆士");
        }
        System.out.println(strings);//[科比, 韦德, 博士], 说明删除成功
    }
    @Test
    public void testListRemove4(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方法4: 倒循环删除
        for (int i = strings.size()-1; i >= 0; i--){
            String s = strings.get(i);
            if ("詹姆士".equals(s)){
                strings.remove(s);
            }
        }
        System.out.println(strings);//[科比, 韦德, 博士], 说明删除成功
    }
    @Test
    public void testListRemove5(){
        List<String> strings = new ArrayList<>();
        strings.add("科比");
        strings.add("韦德");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("詹姆士");
        strings.add("博士");
        strings.add("詹姆士");
        System.out.println(strings);
        //删除方法5: 循环时如果命中目标下标不动
        for (int i = 0; i < strings.size(); i++){
            String s = strings.get(i);
            if ("詹姆士".equals(s)){
                strings.remove(s);
                i--;
            }
        }
        System.out.println(strings);//[科比, 韦德, 博士], 说明删除成功
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用List的remove(Object obj)方法删除指定元素。例如,如果要删除List的元素"apple",可以使用以下代码: List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); list.remove("apple"); 执行完毕后,List就只剩下"banana"和"orange"两个元素了。需要注意的是,如果List有多个相同的元素,remove方法只会删除第一个匹配的元素。如果要删除所有匹配的元素,可以使用循环遍历List并调用remove方法。 ### 回答2: 集合是Java常用的数据结构,它包含了一组元素,这些元素可以是同一类型,也可以是不同类型。而List是Java常用的集合之一,它可以存储多个元素,并且可以根据下标(index)对元素进行访问。在List,我们可以使用remove方法删除指定位置的元素,也可以使用removeAll方法删除指定集合的所有元素,但是如何删除指定元素呢? 在List,使用remove方法删除指定元素,需要先遍历List寻找到需要删除的元素,然后再使用remove方法删除。例如,我们有如下ListList<String> list = new ArrayList<String>(); list.add("apple"); list.add("banana"); list.add("orange"); 如果我们需要删除list的"apple"元素,可以使用以下代码实现: for (Iterator<String> it = list.iterator(); it.hasNext();) { String s = it.next(); if (s.equals("apple")) { it.remove(); } } 上述代码,我们使用了Iterator迭代器来遍历List,然后对每一个元素进行判断,如果是需要删除的元素,则使用Iterator的remove方法进行删除。 除了使用Iterator进行删除外,我们还可以使用Java 8引入的Stream API来删除指定元素。例如,我们有如下ListList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); 如果我们需要删除list的偶数元素,可以使用以下代码实现: list = list.stream().filter(n -> n % 2 != 0).collect(Collectors.toList()); 上述代码,我们使用了Stream API的filter方法,过滤出满足指定条件的元素,再通过collect方法将过滤后的元素重新收集到List。 总之,在List删除指定元素有多实现方式,开发者可以根据具体需求来选择合适的方法。 ### 回答3: 在JavaList接口是一有序的集合,它允许我们在其存储和操作一组元素。List接口提供了许多方法,其一个是remove(Object obj)方法,用于从List删除指定的元素。 为了在List删除指定元素,我们需要先创建List对象并向其添加一些元素。然后我们可以使用remove(Object obj)方法List删除指定的元素。该方法会从List查找并删除第一个匹配的元素。如果List不存在指定的元素,则该方法不会进行任何操作。 下面是一个示例,演示如何在List删除指定元素: ``` import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { // create a list of strings List<String> list = new ArrayList<>(); // add some strings to the list list.add("apple"); list.add("banana"); list.add("pear"); list.add("orange"); // print the original list System.out.println("Original list: " + list); // remove the element "pear" from the list boolean removed = list.remove("pear"); // print the updated list if (removed) { System.out.println("Updated list: " + list); } else { System.out.println("Element not found in the list"); } } } ``` 在上面的示例,我们首先创建一个List<String>对象,并向其添加一些字符串。然后,我们使用remove(Object obj)方法List删除指定的元素。在本例,我们删除了"pear"这个元素。最后,我们打印更新后的列表。 需要注意的是,List的元素可以根据它们的索引位置进行删除,使用remove(int index)方法。此外,我们还可以使用removeAll(Collection<?> c)方法List删除一个集合的所有元素,或使用clear()方法List删除所有元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值