认识对象(七)-数组的复制

数组的复制

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

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值