I have an ArrayList<String> that I'd like to return a copy of. The ArrayList clone method has the following signature:
public Object clone()
After I call this method, how do I cast the returned Object back to a ArrayList<String>?
I have an ArrayList<String> that I'd like to return a copy of. The ArrayList clone method has the following signature:
public Object clone()
After I call this method, how do I cast the returned Object back to a ArrayList<String>?
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
I find using addAll works fine.
ArrayList(String) copy = new ArrayList(String)();
copy.addAll(original);
parentheses are used rather than the generics syntax
I think this should work:
ArrayList<String> orig = new ArrayList&<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()
I think this should do the trick using the Collections API:
Note: the copy method runs in linear time.
//assume oldList exists and has data in it.
List<String> newList = new ArrayList<String>();
Collections.copy(newList, oldList);
Why would you want to clone? Creating a new list usually makes more sense.
List<String> strs;
...
List<String> newStrs = new ArrayList<String>(strs);
Job done.
Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.
Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.