Java ArrayList:创建数组的副本并使用旧的分隔,但不要创建新对象 [英] Java ArrayList: create a copy of array and use seperate from old, but don't create new objects
问题描述
例如,我有一个ArrayList:
For example, I have an ArrayList:
ArrayList<Animal> zoo = new ArrayList<Animal>();
// some code to add animals to zoo
我想创建一个这样的副本旧动物园
到新动物园
,我可以使用remove / add ...来处理这个新动物园。(和当然,它不会影响老动物园)。因此,我有一种方法:创建新动物园,克隆旧动物园中的每只动物(这意味着创建动物对象)。
所以,它太慢了。
I want to create a copy of this old zoo
to new zoo
, and I can use remove/add... to process this new zoo.(and of course, it will not affect to old zoo). So, I have a way that: create new zoo that clone each animals in old zoo (it means create animal objects).
So, it too SLOW.
我有另一种方式:创建旧动物园的每只动物的参考并复制到新的动物园。所以,新的动物园只是参考动物园的动物。所以,每次我删除/添加,...它只是删除对动物对象的引用。没有影响旧动物园,没有创建新对象。
I have an another way: create a reference of each animals of old zoo and copy to new zoo. So, new zoo just hold reference to animals of zoo. So, each time I remove/add,... It just delete reference to animal objects. No affect old zoo, and NO CREATE a new object.
但是,我不知道如何用Java做到这一点。请教我。
But, I don't know how to do it in Java. Please teach me.
谢谢:)
推荐答案
这是非常的简单的Java:
This is very simple in Java:
ArrayList<Animal> copy = new ArrayList<Animal>(zoo);
构造函数 ArrayList< T>(集合<?extends E> c)
执行您作为参数提供的列表的浅拷贝,这正是您要查找的语义。
The constructor ArrayList<T>(Collection<? extends E> c)
performs a shallow copy of the list that you supply as parameter, which is precisely the semantics that you are looking for.
这篇关于Java ArrayList:创建数组的副本并使用旧的分隔,但不要创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!