-1

Here is what I have to do:

Instantiates a new list array and copies the elements of the existing list array to the new list array. The list array instance variable becomes a pointer to the new list array.

I am working with array lists and methods. I have an array list with some numbers. I took numbers from that list but I don't know how to put the numbers that I took into a new array list.

Dekart Kosa
  • 39
  • 2
  • 9

3 Answers3

0

HI Please check the below code.

    ArrayList<Integer> oldlist = new ArrayList<>();
    oldlist.add(0);
    oldlist.add(1);
    oldlist.add(2);
    oldlist.add(3);

    ArrayList<Integer> newList = new ArrayList<>();
    newList.addAll(oldlist);
RaghavPai
  • 652
  • 9
  • 14
0

This is a basic problem in programming. It is usually called "iterating" or more specifically here: "iterating through / over a collection".

A classic way in Java would be:

ArrayList<Stuff> list2 = new ArrayList<>();
for (Stuff thing : list1) list2.add(thing);

You can read the second line as: "For each thing, of class Stuff, in list1, do..." The thing you want to do, is calling addon the second list.

As of Java7 you could do:

 list1.forEach((thing) -> list2.add(thing));
Stefan Fischer
  • 363
  • 4
  • 19
0

Or even simpler:

ArrayList<Integer> newList = new ArrayList<>(oldList);
Grisgram
  • 3,105
  • 3
  • 25
  • 42
  • Wow... why downvote? At least a comment would be nice... I use this hundred times in my apps. Works fine. What is wrong with that? – Grisgram Mar 05 '17 at 07:12