2017-09-23 59 views
-2

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

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

现在在这里,我想在B类是new_array应该是包含在A级相同的元素阵列

注: 我要复制,但我们需要注意的是,当我们在复制数组中进行任何更改时,更改应该“不”反映在原始数组中。

+0

为什么不只是继承'array'? –

+0

如何继承数组? – Jorvis

+0

您继承其他任何东西的方式都一样。 –

回答

0

学习,网上冲浪后,我终于学会了如何在不使用循环复制数组。 解决方案如下:

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

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

0

试试这个:

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类领域

如果不加修饰的公共或受保护的数组字段像protected int array[];在A类中,确保将2个类放在同一个文件夹/包中。

+0

好吧,我明白了你的观点。 – Jorvis

+0

现在我想要问一个问题,假设我想对一个数组进行排序,但不想在给定数组中执行任何更改。那么,该怎么办? – Jorvis

+0

@Jorvis像这样。 'Arrays'是一个特殊的util类,它包含大量静态方法来处理数组。 –

0

类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(); 
} 

}

+0

只是将值数组赋给空数组,数据将被复制到新的数组变量中 –

+0

但是对于您的解决方案,假设我想对给定数组执行排序,但希望给定数组保持不变,那么您的复制解决方案将不会工作。 – Jorvis

0
// 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]); 
     } 
    } 
} 
相关问题