场景描述

在做需求中,有很多情况会出现 对一个list遍历并过滤掉其中特定的数据 这种场景 。但是按照平常的使用方式,发现报错了。

public static void main(String[] args) {
String str1 = new String("abcde");
String str2 = new String("abcde");
String str3 = new String("abcde");
String str4 = new String("abcde");
String str5 = new String("abcde");
List list = new ArrayList();
list.add(str1);
list.add(str2);
list.add(str3);
list.add(str4);
list.add(str5);

System.out.println("list.size()=" + list.size());
for (int i = 0; i < list.size(); i++) {
if (((String) list.get(i)).startsWith("abcde")) {
list.remove(i);
}
}
System.out.println("after remove:list.size()=" + list.size());
}

  运行结果不是:

  list.size()=5

  after remove:list.size()=0

  居然是:

  list.size()=5

  after remove:list.size()=2

原因:List每remove掉一个元素以后,后面的元素都会向前移动,此时如果执行i=i+1,则刚刚移过来的元素没有被读取。

源码分析

查看arrayList源码如下

    public E remove(int index); //执行删除指定位置的元素的功能
public boolean remove(Object o) //执行删除指定元素的功能

  remove(int index)在删除指定index位置时有以下3步

    • 先获取指定位置的元素用于返回值
    • 将指定位置以后的每个元素向前挪一位覆盖
    • 将数据最后一位 元素置空并将size减1
    public E remove(int index) {
RangeCheck(index); modCount++;
E oldValue = (E) elementData[index]; int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work return oldValue;
}

remove(Object o)

  判断object o 是否为null 如果为null 用 ==来判断,如果不为null 用 equals来判断引用是否相同

  从第一个找到即删除并返回

    public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
} /*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}

 

删除 List 中的元素会产生两个问题:

  1. 删除元素后 List 的元素数量会发生变化;
  2. 对 List 进行删除操作可能会产生并发问题;

 

解决方案

倒过来遍历

  1.倒过来遍历list

  for (int i = list.size()-1; i > =0; i--) {

  if (((String) list.get(i)).startsWith("abcde")) {

  list.remove(i);

  }

  }

  2.每移除一个元素以后再把i移回来

  for (int i = 0; i < list.size(); i++) {

  if (((String) list.get(i)).startsWith("abcde")) {

  list.remove(i);

  i=i-1;

  }

  }

  3.使用iterator.remove()方法删除

  for (Iterator it = list.iterator(); it.hasNext();) {

  String str = (String)it.next();

  if (str.equals("chengang")){

  it.remove();

  }

  }

list.remove的使用分析的更多相关文章

  1. Java ArrayList在foreach中remove的问题分析

    目录 iterator itr.hasNext 和 itr.next 实现 倒数第二个元素的特殊 如何避坑 都说ArrayList在用foreach循环的时候,不能add元素,也不能remove元素, ...

  2. LinkedList add remove get 代码分析

    add void linkLast(E e) { //e 要添加的元素 final Node<E> l = last; // 最后一个元素 final Node<E> newN ...

  3. ThreadLocal源码分析:(三)remove()方法

    在ThreadLocal的get(),set()的时候都会清除线程ThreadLocalMap里所有key为null的value. 而ThreadLocal的remove()方法会先将Entry中对k ...

  4. HashMap源码分析(一)

    前言:相信不管在生产过程中还是面试过程中,HashMap出现的几率都非常的大,因此有必要对其源码进行分析,但要注意的是jdk1.8对HashMap进行了大量的优化,因此笔者会根据不同版本对HashMa ...

  5. Netty源码分析第7章(编码器和写数据)---->第4节: 刷新buffer队列

    Netty源码分析第七章: 编码器和写数据 第四节: 刷新buffer队列 上一小节学习了writeAndFlush的write方法, 这一小节我们剖析flush方法 通过前面的学习我们知道, flu ...

  6. Netty源码分析第8章(高性能工具类FastThreadLocal和Recycler)---->第2节: FastThreadLocal的set方法

    Netty源码分析第八章: 高性能工具类FastThreadLocal和Recycler 第二节: FastThreadLocal的set方法 上一小节我们学习了FastThreadLocal的创建和 ...

  7. JDK源码分析(一)——ArrayList

    目录 ArrayList分析 ArrayList继承结构 ArrayList字段属性 ArrayList构造函数 重要方法 ArrayList Iterator迭代器 总结 ArrayList分析   ...

  8. winston写日志(译)

    使用 有两种方式去使用winston,直接通过默认的logger,或者实例化自己的Logger,前者设计的目的是在你的应用程序中共享logger比较方便. 使用默认Logger 使用默认的logger ...

  9. winston日志管理1

    Usage There are two different ways to use winston: directly via the default logger, or by instantiat ...

随机推荐

  1. Forth 采用Create,Does>定义新的词(word)& 延迟词技术

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  2. 8.7 C++二进制文件读写操作

    参考:http://www.weixueyuan.net/view/6413.html 总结: 二进制文件的读写稍微麻烦一些,对二进制文件的读写同样需要打开文件和关闭文件,打开和关闭方式与文本文件相同 ...

  3. excel导入数据库实例(含源码 超级详细适合新手)

    (案例的源码在我的百度网盘里,需要的朋友可以加我微信分享,gqljxg1514) 所有文件一览: 运行结果图: 1,首先创建实体类Student.java package com.b510.excel ...

  4. Address localhost:1099 is already in use

    在 ItelliJ idea中创建了Servlet,启动tomcat时系统报错: Error running Tomcat 7.0.47: Address localhost:1099 is alre ...

  5. jQuery-2.DOM---创建节点及节点属性

    DOM创建节点及节点属性 通过JavaScript可以很方便的获取DOM节点,从而进行一系列的DOM操作.但实际上一般开发者都习惯性的先定义好HTML结构,但这样就非常不灵活了. 试想下这样的情况:如 ...

  6. flask自定义转换器

    根据具体的需求,有些时候是需要用到正则来灵活匹配URL,但是Flask的路由匹配机制是不能直接在路由里直接写正则的,这时候就需要使用转换器! Flask的默认转换器: DEFAULT_CONVERTE ...

  7. 让你简洁清晰真正的了解什么是JavaSCript

    学习JavaScript高级程序设计第三版第一步.JavaScript简介不光在这一本说介绍,很多书都提及到,我就简单的把重点记录下来,当做整理吧,以便自己及大家观看. 1995年,我出生了,Java ...

  8. 《从Lucene到Elasticsearch:全文检索实战》学习笔记二

    今天我给大家讲讲分词算法 分词算法概述:词是语义的最小单位.分词对搜索引擎的作用很大,可以促进搜索引擎程序自动识别语句的含义,可以提高搜索结果的匹配度,分析的质量也将直接影响了搜索结果的精确度.分词存 ...

  9. PTA——黑洞数

    PTA 7-44 黑洞数 我的程序,一个用例通不过 #include<stdio.h> void sort(int *a,int n); int main() { ; scanf(&quo ...

  10. linux sar命令详解

    sar(System Activity Reporter系统活动情况报告)是目前 Linux 上最为全面的系统性能分析工具之一,可以从多方面对系统的活动进行报告,包括:文件的读写情况.系统调用的使用情 ...