如何将 java.util.List 复制到另一个 java.util.List [英] How to copy a java.util.List into another java.util.List
问题描述
我有一个从 Web 服务填充的 List
.我想将该列表的内容复制/克隆到相同类型的空列表中.谷歌搜索复制列表建议我使用 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
>) 一个 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屋!