java 如何将超类中的数组元素复制到子类中的数组中?

How to copy elements of an array in superclass into an array in subclass in java?

例如:

class A
{
    int array[] = {1,2,3,4,5}
}
class B extends A
{
    int new_array[];
}

现在,我希望 class B 中的 new_array 应该包含与 class A 中的数组相同的元素。

注意: 我想复制,但要注意当我们在复制的数组中进行任何更改时,更改应该 "not" 反映在原始数组中的情况。

试试这个:

public class A {
  int arrayA[] = {1,2,4,5,3}; //unsorted array
}

public class B extends A {
  int arrayB[];

  public void exampleOfCopySortPrint() {
    arrayB = Arrays.copyOf(arrayA, 5); // copy the values of arrayA into arrayB
    // arrayB is now an entirely new array

    Arrays.sort(arrayB); // this sorts the array from small to large

    // print all elements in arrayB
    for (int i : arrayB) {
      System.out.println(i); // 1, 2, 3, 4, 5 (sorted)
    }
  }
}

您不需要在 class B 中也添加字段。

如果你不添加修饰符 public 或像 protected int array[]; in class A 那样在数组字段上保护,请确保将 2 classes在同一个 folder/package.

class一个{

int array[] = {1, 2, 3, 4, 5};

}

class B 扩展 A {

int new_array[] = array;

public void afterCopyArrayPrint() {
    for (int i : new_array) {
        System.out.println(i);
    }

}

}

public class ArrayTest {

public static void main(String[] args) {
    B ob = new B();
    ob.afterCopyArrayPrint();
}

}

// TRY THIS
public class Array 
{
    int[] a = {1, 2, 3, 4, 5};
    int length = a.length;
}

class Array2 extends Array 
{
    int[] newArray = new int[super.length];

    public static void main(String[] args)
    {
        Array obj = new Array();
        Array2 obj2 = new Array2();
        for (int i = 0; i < obj.length; i++) {
            obj2.newArray[i] =obj.a[i];
            System.out.println(obj2.newArray[i]);
        }
    }
}

经过学习和网上冲浪,我终于学会了如何不使用循环来复制数组。 解决方法如下:

class A
{
    int array[] = {1, 2, 3, 4, 5};
}
class B extends A
{
    int copyArray[] = array.clone();
}

我发现这个 clone() 方法非常有用!