Sunday 23 October 2016

variables - How does pointing to objects work in java?

Because Java Array is considered Reference Object.


int[] b = a;    // variable 'b' points same memory location with 'a'

If you want to copy all value of a, write code below


@Test
public void arrayCopy1() {
int[] a = {1, 2, 3};
int[] b = a;
System.out.println(a); //Point [I@64a294a6
System.out.println(b); //Point [I@64a294a6
printArrayValues(a); //[1,2,3]
printArrayValues(b); //[1,2,3]
a[0] = 10;
printArrayValues(a); //[10,2,3]
printArrayValues(b); //[10,2,3]
}
@Test
public void arrayCopy2() {
int[] a = {1, 2, 3};
int[] b = Arrays.copyOf(a, a.length);
System.out.println(a); //Point [I@64a294a6
System.out.println(b); //Point [I@7e0b37bc
printArrayValues(a); //[1,2,3]
printArrayValues(b); //[1,2,3]
a[0] = 10;
printArrayValues(a); //[10,2,3]
printArrayValues(b); //[1,2,3]
}
private void printArrayValues(int[] arr) {
System.out.print("[");
for(int i = 0 ; i < arr.length ; i++) {
System.out.print(arr[i]);
if (i != arr.length-1)
System.out.print(",");
}
System.out.println("]");
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...