Reputation: 30276
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 :)
Upvotes: 1
Views: 308
Reputation: 53829
Simply try :
ArrayList<Animal> newZoo = new ArrayList<Animal>(oldZoo);
Upvotes: 5
Reputation: 726589
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.
Upvotes: 6