Java ArrayList: create a copy of array and use seperate from old, but don't create new objects

血红的双手。 提交于 2019-12-23 01:52:15

问题


For example, I have an ArrayList:

ArrayList<Animal> zoo = new ArrayList<Animal>();
// some code to add animals to zoo

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.

But, I don't know how to do it in Java. Please teach me.

Thanks :)


回答1:


This is very simple in Java:

ArrayList<Animal> copy = new ArrayList<Animal>(zoo);

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.




回答2:


Simply try :

ArrayList<Animal> newZoo = new ArrayList<Animal>(oldZoo);


来源:https://stackoverflow.com/questions/10124333/java-arraylist-create-a-copy-of-array-and-use-seperate-from-old-but-dont-crea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!