- 浏览: 285185 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
lsy812198178:
写的很好,有收获
Java内部类的作用 -
JsonLiangyoujun:
关于第四点,同时继承一个类和实现一个接口的话,重写的应该是父类 ...
Java内部类的作用 -
chenluhe123:
非常感谢楼主分享,浅显易懂
Java内部类的作用 -
唐予之.:
学有所获,非常感谢
Java内部类的作用 -
o22221234:
...
Java内部类的作用
import java.util.*;
public class object {
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,则刚刚移过来的元素没有被读取。
解决方法:
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或者说在遍历集合过程中,执行了删除动作就会报错
工作中碰到个ConcurrentModificationException。代码如下:
List list = ...;
for(Iterator iter = list.iterator(); iter.hasNext();) {
Object obj = iter.next();
...
if(***) {
list.remove(obj);
}
}
在执行了remove方法之后,再去执行循环,iter.next()的时候,报java.util.ConcurrentModificationException(当然,如果remove的是最后一条,就不会再去执行next()操作了)
下面来看一下源码
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
public interface Collection<E> extends Iterable<E> {
...
Iterator<E> iterator();
boolean add(E o);
boolean remove(Object o);
...
}
这里有两个remove方法
接下来来看看AbstractList
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//AbstractCollection和List都继承了Collection
protected transient int modCount = 0;
private class Itr implements Iterator<E> { //内部类Itr
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification(); //特别注意这个方法
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet); //执行remove对象的操作
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount; //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
throw new ConcurrentModificationException();
}
}
}
remove(Object o)在ArrayList中实现如下:
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 void fastRemove(int index) {
modCount++; //只增加了modCount
....
}
所以,产生ConcurrentModificationException的原因就是:
执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
要避免这个Exception,就应该使用remove()方法。
这里我们就不看add(Object o)方法了,也是同样的原因,但没有对应的add()方法。一般嘛,就另建一个List了
下面是网上的其他解释,更能从本质上解释原因:
Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
[转]http://www.qqread.com/java/2010/08/y495083.html
发表评论
-
org.springframework.dao.InvalidDataAccessResourceUsageException: could not inser
2011-03-10 21:50 1290最后解决是把配置文件中主键生成策略由sequence改为 ... -
详细介绍Spring事务管理
2011-02-25 00:14 980在学习spring事务管 ... -
JavaScript位置存放
2011-02-17 19:30 989[装]:http://blog.sina.com.cn/s/b ... -
spring quartz自动发送邮件
2011-02-15 18:15 1060http://static.springsource.org/ ... -
在Spring中使用javaMail的项目发布问题解决
2011-02-15 14:00 1068org.springframework.beans.facto ... -
struts2.0 action转跳到jsp页面css失效解决方案
2011-02-14 19:40 1810像页面转跳失效问题肯定是路径的问题。建议改相对路径为绝对路径 ... -
org.hibernate.exception.ConstraintViolationException: could not insert: [com.tes
2011-02-12 17:33 1854数据库中有字段设置long varchar 用hiberna ... -
错误:The type javax.servlet.ServletContext cannot be resolved
2011-01-06 21:30 2932为获取服务器端项目根路径 来源:http://blog.cs ... -
项目开发记录
2011-01-06 21:11 955有机会好好看看 http://tianhandigeng.i ... -
在Struts 2中实现文件上传
2011-01-06 17:06 824http://www.blogjava.net/max/arc ... -
Struts2 OGNL表达式的使用
2011-01-05 19:12 4756OGNL全名Object Graph Navigati ... -
Hibernate分页实现
2011-01-04 16:30 845Dao写好了,具体分页是照着他实现的,很不多,方便简单易懂 h ... -
Action从jsp获取url的参数
2011-01-04 12:25 1283String [] ee=(String []) Action ... -
奇怪的错误,待解决
2011-01-03 21:08 1367感觉什么都没做今天,就出现了这个错: org.hiberna ... -
Can't create DB2 tables: Exception testing case sensitivity
2011-01-03 14:39 1346$ ./repotools.sh -createTables ... -
Jsp遍历List输出,超弱智的问题
2011-01-02 21:39 1926一直报错: org.apache.jasper.JasperE ... -
struts2默认拦截器详细说明
2011-01-01 20:46 1028http://hi.baidu.com/zkban/blog/ ... -
request.getAttribute() 和 request.getParameter() 有何区别?
2010-12-31 09:14 2026Request.getAttribute()是提取自己设置的值 ... -
DB2 备份和恢复
2010-12-30 20:06 1144DB2 备份和恢复 备份和 ... -
执行 DB2 reorgchk
2010-12-30 19:47 4307执行 DB2 reorgchk db2 reorgchk 命令 ...
相关推荐
容易出现的问题就是: for x in nums: 我们通常尽量避免修改一个正在进行遍历的列表,可以使用切片操作克隆这个list来避免这个问题(浅拷贝) #26 class Solution: def removeDuplicates(self, nums: List[int]) -> ...
第三讲 Linux下的网络服务,配置问题和常用工具.................................................................24 一.Linux下的网络服务.....................................................................
impossameule-list可以进行检索工作impossameule-tag可以进行相同的操作,但是具有方便的界面以获取更多分类的结果。请注意,由于各种在线代码的启发,服务器端不是用php编写的,但是协议很容易被反向滴水。 $ ...
无非是Set不能含有重复的Item的特性,Set有初始化、Add、Clear、Remove、Contains等操作。接下来看具体的实现方式分析吧。 实现 仍然按照已有的编程经验来联想如何实现基本Set功能,在Java中很容易知道HashSet的...
在VC/MFC用CDC绘图时,频繁的刷新,屏幕会出现闪烁的现象,CPU时间占用率相当高,绘图效率极低,很容易出现程序崩溃。及时的释放程序所占用的内存资源是非常重要的。 在程序中使用到的链表、刷子等占用内存资源...
* In your Delphi/C++Builder project options, remove as much forms as possible from the Auto-Create option. Create your forms dynamically. *在你的delphi/C++Builder工程选项中,尽可能地不要使用自动创建...
内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供的GC功能可以自动监测对象是否超过作用域从而达到自动回收内存的目的,Java语言没有提供释放已分配内存的...
内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供的GC功能可以自动监测对象是否超过作用域从而达到自动回收内存的目的,Java语言没有提供释放已分配内存的...
GoF 的设计模式表面上好象也是一种具体的"技术",而且新的设计模式不断在出现,设计模式自有其自己的发展轨道,而这 些好象和 J2EE .Net 等技术也无关! 实际上,GoF 的设计模式并不是一种具体"技术",它讲述的是...
8.Flash中Remove movie clip指的是什么? A. 删除已复制的电影夹子 B. 删除电影夹子 C. 移动电影夹子 D. 复制电影夹子 9.Flash可接受的当鼠标放在按钮上时产生效果的鼠标操作是哪个? A. Press B. Release C....
利用C++的封装性开发者可以更容易理解和操作各种窗口对象;利用C++的派生性开发者可以减少开发自定义窗口的时间和创造出可重用的代码;利用虚拟性可以在必要时更好的控制窗口的活动。而且C++本身所具备的超越C语言的...
的时候那个add file步骤,也可以点选Project->Add/Remove Files in Project进行操作)如图 22 图22 将原来的顶层图打包,作为下载的一个模块,然后添加下载电路。如下图所示: 由于我们下载经常要用到...
i++) //这里写成0x40也没有问题,我看他这个表应该长度为0x40,但网上说PspCreateProcessNotifyRoutine表长 度在win2K下为8,xp下为多少,我没有找到资料,懒得去分析代码找出他的长度 { //if( 0 == pRoutineList[i] )...