【问题标题】:How to copy elements of an array in superclass into an array in subclass in java?java - 如何将超类中的数组元素复制到子类中的数组中?
【发布时间】:2018-03-05 00:26:24
【问题描述】:

例如:

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

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

注意: 我想复制,但想处理这种情况,当我们对复制的数组进行任何更改时,更改应该“不会”反映在原始数组中。

【问题讨论】:

  • 为什么不直接继承array
  • 如何继承数组?
  • 以同样的方式继承其他任何东西。
  • 如果你能告诉我该怎么做,我会很高兴的。实际上,目前我正在学习Java。所以,目前对这种语言不太适应。
  • 很多 Java 教程都介绍了继承。我建议你从那里开始你的研究。

标签: java arrays clone subclass superclass


【解决方案1】:

在学习和上网之后,我终于学会了如何在不使用循环的情况下复制数组。 解决方法如下:

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

我发现这个 clone() 方法真的很有帮助!

【讨论】:

    【解决方案2】:

    试试这个:

    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)
        }
      }
    }
    

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

    如果您没有在 A 类中的 protected int array[]; 等数组字段上添加修饰符 public 或 protected,请确保将这 2 个类放在同一个文件夹/包中。

    【讨论】:

    • 现在我想让你再问一件事,假设我想对一个数组进行排序,但不想对给定的数组进行任何更改。那么,那该怎么办呢?
    • @Jorvis 就像这样。 Arrays 是一个特殊的 util 类,它包含大量静态方法来操作数组。
    【解决方案3】:
    // 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]);
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      A类{

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

      }

      B 类扩展 A {

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

      }

      公共类 ArrayTest {

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

      }

      【讨论】:

      • 只需将值数组分配给空数组,数据将被复制到新的数组变量中
      • 但是使用您的解决方案,假设当我想对给定数组执行排序但希望给定数组保持不变时,您的复制解决方案将不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多