0

i'm trying to make a simple copy of an array, and i'm failing pretty hard in it.

This is what i have so far.

      Scanner scanner = new Scanner(System.in);
        int[] numbers = new int[5];
        for (int i = 0; i < 5; i++){
            numbers[i] = scanner.nextInt();
        }
        int[] newList = new int[5];

        newList = numbers; //it's not going well over here
  • I did, but i simply can't figure it out yet. Arrays are really difficult for me – CoffeeCup.optix Jan 03 '20 at 14:49
  • You don't "copy an array by reference." If you copy the reference (`newList = numbers`), you're using two variables to refer to the **same** array (and you don't need to initialize `newList` first, since you're not using the array you created doing that). To *copy* the array instead, you'd use a loop or [`System.arraycopy`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/System.html#arraycopy(java.lang.Object,int,java.lang.Object,int,int)). See the [linked question](https://stackoverflow.com/questions/5785745/make-copy-of-an-array)'s answers for details. – T.J. Crowder Jan 03 '20 at 14:50
  • @T.J.Crowder the thing is, i have a sample input of 1,2,3,4,5 with this code, and the sample output has to be the same. which is: 1,2,3,4,5. the only edit i have to make is the bottom line according to the exercise. but i don't see how you can only make a chance from the last line of code to make an actual copy of the array – CoffeeCup.optix Jan 03 '20 at 14:59
  • @CoffeeCup.optix - You change it to a call to `arraycopy`; see the accepted answer to the linked question. – T.J. Crowder Jan 03 '20 at 15:13

0 Answers0