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

Asked

Viewed 385 times

0

Why the value of Numbers[0] changes to 3 after executing the code line 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);
}

1 answer

1


In Java, when you assign an array to another array, as in this line:

int [] New_Numbers = Numbers;

You’re not creating a copy of the array, you’re just 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], 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 an array to other array in java - Stack Overflow

  • I get it. Thank you.

  • Diogo, the best way to thank for an answer is to mark it as accepted by clicking on the visa sign ( ). But do this only if any answer has answered your original question. When you reach 15 reputation points you can also vote in favour of an answer or question. See: Someone answered me and Why vote?. Also do the tour, for an initial explanation of how the site works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.