如:如何将超类中数组的元素复制到java中的子类中的数组中?
class A
{
int array[] = {1,2,3,4,5}
}
class B extends A
{
int new_array[];
}
现在在这里,我想在B类是new_array应该是包含在A级相同的元素阵列
注: 我要复制,但我们需要注意的是,当我们在复制数组中进行任何更改时,更改应该“不”反映在原始数组中。
如:如何将超类中数组的元素复制到java中的子类中的数组中?
class A
{
int array[] = {1,2,3,4,5}
}
class B extends A
{
int new_array[];
}
现在在这里,我想在B类是new_array应该是包含在A级相同的元素阵列
注: 我要复制,但我们需要注意的是,当我们在复制数组中进行任何更改时,更改应该“不”反映在原始数组中。
学习,网上冲浪后,我终于学会了如何在不使用循环复制数组。 解决方案如下:
class A
{
int array[] = {1, 2, 3, 4, 5};
}
class B extends A
{
int copyArray[] = array.clone();
}
我发现这个clone()方法真的很有帮助!
试试这个:
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个类放在同一个文件夹/包中。
类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();
}
}
只是将值数组赋给空数组,数据将被复制到新的数组变量中 –
但是对于您的解决方案,假设我想对给定数组执行排序,但希望给定数组保持不变,那么您的复制解决方案将不会工作。 – Jorvis
// 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]);
}
}
}
为什么不只是继承'array'? –
如何继承数组? – Jorvis
您继承其他任何东西的方式都一样。 –