每天学习十分钟15之Java学习笔记

Java基础知识:数组复制

int[] scores1 = {102318};
int[] scores2 = scores1;

数组是对象,上面的程序片段只是将scores1参考的数组对象,也给scores2参考。如果要做到数组复制,基本做法是另行建立新数组。如下:

int[] scores1 = {102318};
int[] scores2 = new int[scores.length];
for (int i = 0; i < scores1.length; i++) {
    scores2[i] = scores1[i];
}

以上代码通过建立一个长度与scores1相同的新数组,再逐一访问scores1每个索引元素,并指定给scores2对应的索引位置。事实上,不用自行使用循环做值的复制,而可以使用System.arraycopy() 方法,这个方法会使用原生方式复制每个索引元素,比自行使用循环来得快:

int[] scores1 = {102318};
int[] scores2 = new int[scores.length];
System.arraycopy(scores1, 0, scores2, 0, scores1.length);

System.arraycopy() 的五个参数分别是来源数组、来源起始索引、目的数组、目的起始索引、复制长度。如果使用JDK6以上,还有个更方便的Arrays.copyOf() 方法,你不用另外建立新数组,Arrays.copyOf会帮你建立、如下:

int[] scores1 = {102318};
int[] scores2 = Arrays.copyOf(scores1, scores1.length);
// 下面代码不会影响scores1参考的数组对象
scores2[0] = 99;

在Java中,数组一旦建立,长度就固定了.
数组复制中还分为浅层复制(Shallow copy) 和深层复制(Deep copy)。无论System.arraycopy() 还是Array.copyOf 都是浅层复制,因为复制过程中只是将源索引参考的对象给目标对象的索引去参考,并没有复制对象,术语上来说是复制参考。下面两段代码片段来解释:

class Clothes {
     String color;
     char size;
     Clothes(String color, char size) {
     this.color = color;
     this.size = size;
     }
}
public class shallowCopy {
  pubilc static void main(String[] args) {
     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对象
   c1[0].color = "yellow"
   System.out.println(c2[0].color);
}

// 输出结果为yellow。
class Clothes2 {
     String color;
     char size;
     Clothes2(String color, char size) {
     this.color = color;
     this.size = size;
     }
}
public class deepCopy {
  pubilc static void main(String[] args) {
     Clothes2[] c1 = {new Clothes2("red", "L"), new Clothes2("blue", "M")};
     Clothes2[] c2 = new Clothes2(c1.length);
     for(int i = 0; i < c1.length; i++) {
         // 自行复制元素
         Clothes2 c = new Colthes2(c1[i].color, c1[i].size);
         c2[i] = c;
     }
   }
   // 通过c1修改索引0对象
   c1[0].color = "yellow"
   System.out.println(c2[0].color);
}

// 输出结果为red
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值