`

Java List Copy,Remove容易出现的问题

    博客分类:
  • JAVA
 
阅读更多

   懒程序员,在代码越写越多的情况下,总想着使用把代码精简一下,能不写if else的,能不写for循环的尽量不想写,但是遇到的问题都要解决的呀,因此调用同逻辑的已存在方法便是首选。

  今天就集合类(List)两个容易出错的方法做个记录,可以引以为戒,并且也提供正常的使用方式, 都是在java.utils包,方便使用。



package com.longer.list;  
  
import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.Collections;  
import java.util.Iterator;  
import java.util.List;  
  
import junit.framework.TestCase;  
  
/** 
 *  
 * @author Longer 
 * Apr 23, 2010 2:49:13 PM 
 */  
public class ListTest extends TestCase {  
  
    class TempBean{  
          
        public TempBean( String str ){  
            this.str = str;  
        }  
          
        String str;  
  
        public String getStr() {  
            return str;  
        }  
  
        public void setStr(String str) {  
            this.str = str;  
        }  
    }  
      
    List<TempBean> tempList = null;  
    protected void setUp() throws Exception {  
        super.setUp();  
          
        tempList = new ArrayList<TempBean>();  
        tempList.add( new TempBean("1") );  
        tempList.add( new TempBean("2") );  
        tempList.add( new TempBean("30") );  
        tempList.add( new TempBean("31") );  
        tempList.add( new TempBean("3") );  
    }  
  
    protected void tearDown() throws Exception {  
        super.tearDown();  
          
        tempList.clear();  
        tempList = null;  
    }  
      
    public void testRemove1(){  
          
        for (TempBean bean : tempList ) {  
            //exception:java.util.ConcurrentModificationException  
            //tempList.remove( bean );  
        }  
        System.out.println( tempList );  
    }  
      
    public void testRemove2(){  
          
        for (int i = 0; i < tempList.size(); i++) {  
            TempBean bean = tempList.get(i);  
            tempList.remove( i );//or tempList.remove(bean);  
            i--;  
        }  
        System.out.println( tempList );  
    }  
      
    public void testRemove3(){  
          
        System.out.println("before remove:" + tempList );  
        for (Iterator iterator = this.tempList.iterator(); iterator.hasNext();) {  
            iterator.remove();  
            //exception:java.lang.IllegalStateException  
            //tempList.add( new TempBean("") );  
        }  
        System.out.println("after remove:"+ tempList );  
    }  
      
    public void testCopy1(){  
          
        List<TempBean> newList = new ArrayList<TempBean>();  
        //exception:java.lang.IndexOutOfBoundsException: Source does not fit in dest  
        //Collections.copy( newList, tempList );  
    }  
      
    public void testCopy2(){  
          
        List<TempBean> newList = new ArrayList<TempBean>(Arrays.asList(new TempBean[ this.tempList.size()]));  
        Collections.copy( newList, tempList );  
        System.out.println( newList );  
    }  
}  




异常解释:

  1:testRemove1-->java.util.ConcurrentModificationException
  此类的JavaDOC部分原文:
    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible。
  简单翻译:
      检测到一个对象存在同步修改,并且此修改不被允许的情况下,此异常将被方法抛出。

  因此, 可以看出List是不支持同步修改的,其实整个Collection、Map都与List一样的情况,详细的原因得从迭代器Iterator去研究,这里不做分析。大概理解是Iterator在遍历的时间内,其源对象索引发生了改变,导致了不同步现象。

  2)testRemove3-->java.lang.IllegalStateException
  此类的JavaDOC部分原文:
    Signals that a method has been invoked at an illegal or inappropriate time
  简单翻译:
    信息灯,一个方法在非法或者不恰当的时间内被调用。
  因此, 问题的根源同上。

  3)testCopy1-->java.lang.IndexOutOfBoundsException
  Collections.copy JavaDOC部分原文:
    ......The destination list must be at least as long as the source list.......
  简单翻译:
    目的list必须至少要与源list等长。(目的List可以比源List长度长)

  因此, 它这里指的长度是List里的size()方法值,我们都知道new ArrayList()初始化的时候size()等于0,即便是你使用new ArrayList(10)来初始化,也只是预设了一个initialCapacity==10的存储空间,size()还是等于0。因此在使用Collections.copy之前,需要把目的List加一些空的元素,直到目的List的size()值与源List的size()值等长(或更长)。
分享到:
评论

相关推荐

    Java容器.xmind

    List 标记: interface ArrayList 标记: class CRUD : boolean add​(E e) boolean remove​(Object o) E set​(int index, E element) E get​(int index) 底层数组实现,查询快,增删慢 LinkedList 标记: ...

    Java邮件开发Fundamentals of the JavaMail API

    configuring a server to relay messages or to add and remove e-mail accounts. POP POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. ...

    cpp-算法精粹

    Copy List with Random Pointer Linked List Cycle Linked List Cycle II Reorder List LRU Cache Palindrome Linked List 字符串 Valid Palindrome Implement strStr() String to Integer (atoi) Add Binary ...

    python基础2day01.txt

    L.remove(v) L.pop(index) L.sort(reverse=False) L.extend() 深拷贝 和 浅拷贝 copy.deepcopy L.copy() L2 = L 字符串方法: S.split(sep=None) S.join(序列) 列表推导式 [表达式 for 变量 in 可迭代...

    多线程leetcode-leetcode-java:leetcode上的题解,基于java语言

    每天刷点leetcode,基于java语言实现。 leetcode上难度分三档:easy,medium,hard. 如下: easy medium Remove Nth Node From End of List Swap Nodes in Pairs Spiral Matrix Path Sum II Copy List with Random ...

    swing文件拖拽

    import java.util.List; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.Timer; import javax.swing.event.TreeExpansionEvent; import javax.swing.event....

    F1Engine v0.1 alpha

    F1Engine V0.1 alpha版本是我用晚上的业余时间写的一个java文件操作组件,目前只是在原型的测试阶段。 主要的设计目标是:简单方便 可以方便地加到应用中,可以满足日常应用中的大部分应用场景。 二、使用...

    Cisco Packet Tracer7.3.0插件(ActivityGrader_x86_7.3.0.0.zip)

    installed, remove it from the approved list and delete the "extensions\ActivityGrader" folder. Then follow the "Installing Activity Grader" section. Installing Activity Grader ----------...

    Cisco Packet Tracer7.3.0插件(ActivityGrader_x86_64_7.3.0.0.zip)

    installed, remove it from the approved list and delete the "extensions\ActivityGrader" folder. Then follow the "Installing Activity Grader" section. Installing Activity Grader ----------...

    二十三种设计模式【PDF版】

    需要将 J2EE 用对地方,那么只有理解 J2EE 此类框架软件的精髓,那么你才能真正灵活应用 Java 解决你的问题,甚至构架出你自 己企业的框架来。(我们不能总是使用别人设定好的框架,为什么不能有我们自己的框架?) ...

    apktool documentation

    Used with -c / --copy-original on [b]uild unknown = Files / folders that are not part of the standard AOSP build procedure. These files will be injected back into the rebuilt APK. apktool.yml ...

    UE(官方下载)

    Remove blank lines A question we often see is "I have a lot of blank lines in my file and I don't want to go through and manually delete them. Is there an easier way to do this?" The answer is: yes! ...

    VB编程资源大全(英文源码 控制)

    1.x/6.0 (Java) &lt;END&gt;&lt;br&gt;6 , ocxex.zip "This is a quick example I made to show you how to use Events and properties in a OCX."&lt;END&gt;&lt;br&gt;7 , news.exe This control aids as a complete Newsgroup ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control ...

    servlet2.4doc

    Overrides the standard java.lang.Object.clone method to return a copy of this cookie. containsHeader(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of ...

Global site tag (gtag.js) - Google Analytics