Change the first and last element of an array by creating a new array

0

Why does the value of Numbers[0] change to 3 after executing the line of code below?

New_Numbers [0] = Numbers [Numbers.length - 1];

The complete code:

public static void main(String[] args)
{

   System.out.print("Indique o número de elementos do array: ");
   int a = scanner.nextInt();
   int [] Numbers = new int [a];
   System.out.println("Indique os três elementos do array:");
   for ( int i = 0; i < a; i++ )
   {
       System.out.print("Número na posição " + i + " do array: ");
       Numbers [i] = scanner.nextInt();
   }
   int [] New_Numbers = Numbers;
   New_Numbers [0] = Numbers [Numbers.length - 1];
   New_Numbers [New_Numbers.length - 1] = Numbers [0];
   String Numbers_S = Arrays.toString(Numbers);
   String New_Numbers_S = Arrays.toString(New_Numbers);
   System.out.println("Array original: " + Numbers_S);
   System.out.println("Novo array após a troca entre o primeiro e o último elementos: " + New_Numbers_S);
}
    
asked by anonymous 11.11.2018 / 18:24

1 answer

1

In Java, when you assign an array to another array, as in that row:

int [] New_Numbers = Numbers;

You are not creating a copy of the array, you are only passing the same reference to another variable, so the two variables now point to the same array. So when you change the value of New_Numbers[0] , it is automatically changing the value of Numbers[0] , because the two arrays are pointing to the same address in memory.

To make a copy of the array do so:

int[] New_Numbers = Arrays.copyOf(Numbers, Numbers.length);

Source:
problem with assigning array to other array in java - Stack Overflow

    
11.11.2018 / 18:50