0

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.

Dzyuv001
  • 308
  • 5
  • 17
  • I think you can use `clone` to 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. – Pankaj Dubey May 06 '15 at 10:58
  • You want to duplicate `ArrayList` or array? – Aakash May 06 '15 at 10:58

6 Answers6

6

Use

List<Movie> newList = new ArrayList<>(existingList);
Tagir Valeev
  • 92,683
  • 18
  • 210
  • 320
1

You can create a copy of the old ArrayList with:

List<Movie> newList = new ArrayList<Movie>(oldList);

You should know that this creates a shallow copy of the original ArrayList, so all of the objects in both lists will be the same, but the two lists will be different objects.

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
0

Though the question is ambiguous, you can use

List<Integer> newList = new ArrayList<Integer>(oldList); to copy an old List

and

Arrays.copyOf() to copy array.

Aakash
  • 1,915
  • 13
  • 22
0
System.arraycopy()

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Source

KM11
  • 695
  • 6
  • 15
0

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);
}
0

You can get Array from original Array List as below:

Movie movieArray[] = arrayListMovie
    .toArray(new Movie[arrayListMovie.size()]);
Rajesh
  • 2,120
  • 1
  • 11
  • 14