I have an array list that stores objects called Movie. The objects contain variables such as name , date released ,genre etc.. Is there a way to duplicate the array so I can sort it one by one keep the original data unchanged. I will be displaying the data in text areas.
6 Answers
System.arraycopy()
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Comments
Every Collection Class provide a constructor to crate a duplicate collection Object.
List<Movie> newList = new ArrayList<Movie>(oldList);
since newList and oldList are different object so you can also create a clone of this object-
public static List<Movie> cloneList(List<Movie> oldList) {
List<Movie> clonedList = new ArrayList<Movie>(oldList.size());
for (Movie movie: oldList) {
clonedList.add(new Movie(movie));
}
return clonedList;
}
ArrayList is also dynamic array,but if you want to store this in array you can do this as-
int n=oldList.size();
Movie[] copiedArray=new Movie[n];
for (int i=0;i<oldList.size();i++){
copiedArray[i]=oldList.get(i);
}
cloneto duplicate arraylist and create a new with the same data inside it, by this way you will be able to save the memory and a good solution without compromising performance.ArrayListor array?