问题
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