简体   繁体   English

访问另一个类的数组变量

[英]Accessing array variable of another class

Lets say I have a class as below: 可以说我有一个课程如下:

public class class1{

   private int[] array1;

   public class1(){
      array1 = new int[10];
      }

   public int[] getArray(){
      return array1;
      }
}

If I create an instance of this class in another class or in main and use the getArray() method to assign the array to another variable in the upper class and then modify the values of the array there, will the original array values in the first class be modified also? 如果我在另一个类或main中创建此类的实例并使用getArray()方法将数组分配给上层中的另一个变量然后修改那里的数组值,那么原始数组值是否在第一个中班级还要修改吗?

will the original array values in the first class be modified also? 第一类中的原始数组值是否也会被修改?

Yes it will be modified, because what you get in your caller, is not a copy of the array itself, rather you get a copy of the reference to the original array object. 是的,它会被修改,因为你在调用者中获得的不是数组本身的副本,而是获得对原始数组对象的引用的副本。

And, if you modify the array using any reference, the change will be reflected for all the references pointing to the array. 并且,如果使用任何引用修改数组,则将针对指向数组的所有引用反映更改。

yes, the original array values will also be modified. 是的,原始数组值也将被修改。

As you are returning the reference of the array from the method. 当您从方法返回数组的引用时。 The reference is nothing but a pointer to the address of the object. 引用只是指向对象地址的指针。 When you return it from the method, it is assigned to another reference. 从方法返回时,会将其分配给另一个引用。 if you modify any thing using that reference, you are essentially modifying the same array ie the original array. 如果使用该引用修改任何内容,则实质上是修改相同的数组,即原始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM