Repair a memory allocation issue
Please correct the fixMe() method so that arr2 still copies the value of arr1 but when arr1 is changed arr2 stays independent.
Remember: To increase memory access efficiency Java will always check to see if it has an Object in memory first before creating a brand new Object. This can cause problems when setting Objects equal to other Objects.
In the code below you will see that we declare an Object arr1 and then another Object arr2. In this scenario, changing the value of arr1 has the unintended consequence of also changing the value of arr2. This is a product of memory efficiency in Java. It is not creating a new object but rather creating a reference to the original memory location.
Please correct the fixMe() method so that arr2 still copies the value of arr1 but when arr1 is changed arr2 stays independent.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class CodingQuestion {
static void fixMe(int index, int num) {
int[] arr1 = {0, 1, 2, 3, 4};
int[] arr2 = arr1;
for(int i : arr1){
arr2[i] = arr1[i];
}
arr1[index] = num;
System.out.print("arr1: ");
for (int i : arr1){
System.out.print(i + ", ");
}
System.out.print("\n arr2: ");
for (int i : arr2){
System.out.print(i + ", ");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int index = in.nextInt();
int newNumber = in.nextInt();
fixMe(index,newNumber);
}
}
STDOUT
Expected STDOUT
arr1: 0, 1, 2, 3, 10,
arr2: 0, 1, 2, 3, 4,