• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
洗尽铅华终究染懵懂
博客园    首页    新随笔    联系   管理    订阅  订阅

深复制和浅复制

深复制:

System.arraycopy(source array name, starting source element index,

                           target array name, starting target element index,

                           number of elements to be copied);

对复制出来的数组进行操作不会影响源数组,

这种完全的、元素对元素的复制方式称作深复制(deep copy)。

 1 public class JAVA1 {
 2     public static void main(String[] args) {
 3         int i,max;
 4         int[] nums={2,18,1,27,16};
 5         int[] newnums=new int[nums.length];
 6         System.arraycopy(nums,0,newnums,0,newnums.length);
 7         newnums[2]=50;
 8         for(i=0;i<newnums.length;i++)
 9             System.out.println("newnums["+i+"] is "+newnums[i]);
10         System.out.println();
11         for(i=0;i<nums.length;i++)
12             System.out.println("nuns["+i+"] is "+nums[i]);
13     }
14 }

 

 

浅复制:

 1 public class ShallowCopy{
 2     public static void main(String[] args) {
 3         int i;
 4         int[] nums={2,18,1,27,16};
 5         int[] newnums=new int[nums.length];
 6         newnums=nums;
 7         newnums[2]=50;
 8         for(i=0;i<newnums.length;i++)
 9             System.out.println("newnums["+i+"] is "+newnums[i]);
10         System.out.println();
11         for(i=0;i<nums.length;i++)
12             System.out.println("nums["+i+"] is "+nums[i]);
13         }
14 }

赋值语句 newnums=nums; 这个语句完成的任务是把存储在 nums 数组中的地址赋值到引用变量 newnums 中。并没使用 newnums 数组分配的存储空间,所以不需要使用 new 运算符,声明语句 int newnums[]; 就已经足够了。

posted @ 2015-08-07 10:40  洗尽铅华终究染懵懂  阅读(393)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3