Java array of primitive data types

Why does the following code work how does it use reference types rather than primitive types?

int[] a = new int[5]; int[] b = a; a[0] = 1; b[0] = 2; a[1] = 1; b[1] = 3; System.out.println(a[0]); System.out.println(b[0]); System.out.println(a[1]); System.out.println(b[1]); 

And the result: 2 2 3 3 rather than 1 2 1 3

+4
source share
4 answers

The contents of the int array may not be references, but the int [] variables are . By setting b = a , you copy the link, and two arrays point to the same piece of memory.

+6
source

I describe what you are doing here:

  • creating an array of integers int[] a = new int[5];
  • creating a reference to the created array int[] b = a;
  • adding an integer to the array "a", position 0
  • overwrite the previously added integer since b [0] points to the same place as [0]
  • adding an integer to the array "a", position 1
  • rewrite the previously added integer again, since b [1] points to the same place as [1]
+2
source

you are not creating a new instance of int[] b = a

if you need a new instance (and the expected result) add clone() : int[] b = a.clone()
good luck

0
source

Both a and b point to () the same array. Changing the value in a or b will change the same value for another.

0
source

All Articles