Есть важный момент массивов, который часто не учат или пропускают на уроках Java. Когда массивы передаются в функцию, тогда создается другой указатель на тот же массив (тот же указатель никогда не передается). Вы можете манипулировать массивом, используя оба указателя, но как только вы назначите второй указатель новому массиву в вызываемом методе и вернитесь обратно через void к вызывающей функции, тогда оригинальный указатель все еще останется неизменным.
Вы можете напрямую запустить код здесь: https://www.compilejava.net/
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
Demo1.Demo1(Main_Array);
// THE POINTER Main_Array IS NOT PASSED TO Demo1
// A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1
System.out.println("Main_Array = "+Arrays.toString(Main_Array));
// outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
// Since Main_Array points to the original location,
// I cannot access the results of Demo1 , Demo2 when they are void.
// I can use array clone method in Demo1 to get the required result,
// but it would be faster if Demo1 returned the result to main
}
}
public class Demo1
{
public static void Demo1(int A[])
{
int B[] = new int[A.length];
System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Demo2.Demo2(A,B);
System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
A = B;
// A was pointing to location of Main_Array, now it points to location of B
// Main_Array pointer still keeps pointing to the original location in void main
System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// Hence to access this result from main, I have to return it to main
}
}
public class Demo2
{
public static void Demo2(int AAA[],int BBB[])
{
BBB[0] = 9999;
// BBB points to the same location as B in Demo1, so whatever I do
// with BBB, I am manipulating the location. Since B points to the
// same location, I can access the results from B
}
}