java - How to Shallow Copy Array list with full working example -
as java noob spend of day trying find solution easy apply deep copy arraylist. thought had found , posted code example here. found comments below wrong , had produced shallow copy. problem being didn't understand meant deep copy. have edited title , question. code works , might still useful me starting climb learning curve.
the best answer find use foreach statement cycle through contents of 1 array , copy them another. prove works, below small complete test program demonstrate.
package test; import java.util.arraylist; public class arraylistcopy { public static void main(string[] args){ system.out.println("running array copy test"); arraylist < string > arrayfrm; //define 2 arrays arraylist < string > arrayto; arrayfrm = new arraylist<string>(3); //load 1 of them arrayfrm.add("one"); arrayfrm.add("two"); arrayfrm.add("three"); arrayto = new arraylist <string>(3); //create array copy arrayfrm.foreach(item->arrayto.add(item)); // deep copy arrayto.foreach(item->system.out.println(item)); //make sure works } }
in code, deep copy completed 2 lines of code. use size of old array set size of new array. use foreach loop complete deep copy.
newarray = new arraylist <string>( oldarray.size()); oldarray.foreach(item->newarray.add(item));
i haven't tried multi-dimensional array. use other data types, change string meet requirements.
Comments
Post a Comment