数组的复制
package cc.openhome;
import java.util.Arrays;
class Clothes{
String color;
char size;
//建立Clothes的类
Clothes(String a,char b)
{
this.color=a;
this.size=b;
}
}
public class CopyArray {
public static void main(String[] args) {
复制数组
int[] score1={88,81,74,68,78,76,77,85,95,93};
int[] score2=Arrays.copyOf(score1, score1.length);
for(int score:score1)
{
System.out.printf("%3d ",score);
}
验证
System.out.printf("%n更改score2的第三个元素之后的score2:%n");
score2[2]=10;
for(int score:score2)
{
System.out.printf("%3d ",score);
}
System.out.printf("%n更改score2之后,观察score1是否改变:%n");
for(int score:score1)
{
System.out.printf("%3d ",score);
}
java中只要建立数组那么数组的长度就已经确定,如果不确定就用复制数组建立一个全新数组来储存就好
System.out.printf("%n当空间不够时候%n");
int[] score3=Arrays.copyOf(score1, 15);//改变copyof的值
for(int score:score3)
{
System.out.printf("%3d ",score);
}
类类型声明的数组
System.out.println();
System.out.println("类类型");
浅层复制
Clothes[] c1={new Clothes("red",'L'),new Clothes("blue",'M')};
Clothes[] c2=new Clothes[c1.length];
for(int i=0;i<c1.length;i++)
{
c2[i]=c1[i];
}
c1[0].color="yellow";
System.out.println(c2[0].color);
深层复制
Clothes[] c3=new Clothes[c1.length];
for(int j=0; j<c1.length;j++)
{
Clothes c=new Clothes(c1[j].color,c1[j].size);
c3[j]=c;
}
c1[0].color="red";
System.out.println(c3[0].color);
}
}