如何将java.util.List复制到另一个java.util.List中 [英] How to copy a java.util.List into another java.util.List
问题描述
我有一个从Web服务填充的列表< SomeBean>
。我想将该列表的内容复制/克隆到相同类型的空列表中。 Google搜索复制列表建议我使用 Collections.copy()
方法。在我看到的所有示例中,目标列表应包含要进行复制的项目的确切数量。
I have a List<SomeBean>
that is populated from a Web Service. I want to copy/clone the contents of that list into an empty list of the same type. A Google search for copying a list suggested me to use Collections.copy()
method. In all the examples I saw, the destination list was supposed to contain the exact number of items for the copying to take place.
由于我使用的列表是通过Web服务填充的,它包含数百个对象,我不能使用上面的技术。或者我使用它错了!无论如何,为了使它工作,我试图做这样的事情,但我仍然有一个 IndexOutOfBoundsException
。
As the list I am using is populated through a web service and it contains hundreds of objects, I cannot use the above technique. Or I am using it wrong??!! Anyways, to make it work, I tried to do something like this, but I still got an IndexOutOfBoundsException
.
List<SomeBean> wsList = app.allInOne(template);
List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy,wsList);
System.out.println(wsListCopy.size());
我尝试使用 wsListCopy = wsList.subList(0,wsList。 size())
但我在代码中有一个 ConcurrentAccessException
。命中和审判。 :)
I tried to use the wsListCopy=wsList.subList(0, wsList.size())
but I got a ConcurrentAccessException
later in the code. Hit and trial. :)
无论如何,我的问题很简单,如何将我的列表的整个内容复制到另一个列表中?课程。
Anyways, my question is simple, how can I copy the entire content of my list into another List? Not through iteration, of course.
推荐答案
只需使用:
List<SomeBean> newList = new ArrayList<SomeBean>(otherList);
注意:如果修改 otherList
从另一个线程,那么你可能想让 otherList
(甚至 newList
)a CopyOnWriteArrayList
,例如 - 或使用锁原语,例如 ReentrantReadWriteLock 序列化对同时访问的任何列表的读/写访问。
Note: still not thread safe, if you modify otherList
from another thread, then you may want to make that otherList
(and even newList
) a CopyOnWriteArrayList
, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.
这篇关于如何将java.util.List复制到另一个java.util.List中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!