zoukankan      html  css  js  c++  java
  • 数组的复制

    1、四种数组复制方式的逐一详细说明:
    第一种方式利用for循环:
    int[] a = {1,2,4,6};
    int length = a.length;
    int[] b = new int[length];
    for (int i = 0; i < length; i++) {
      b[i] = a[i];
    }

    第二种方式直接赋值:
    int[] array1 = {1,2,4,6};
    int[] array2 = a;
    这里把array1数组的值复制给array2,如果你这样去运行,就会发现此时两个数组的值是一样的。这是传递的是引用(也就是地址),之后改变其中一个数组另一个也会跟着变化。

    第三种方式:
    利用Arrays自带的copyof
    int copy[] = Arrays.copyOf(a, a.length);

    第四种方式:
    利用System.arraycopy()这个函数,从JAVA API中找了一段,大家看一下。
    public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
    参数说明:src     - the source array.  
                指源数组

         srcPos  - starting position in the source array.  
                指要复制的源数组的起始下标

         dest  - the destination array.  
                指目标数组

         destPos - starting position in the destination data.  
                指目标数组复制起始下标

         length  - the number of array elements to be copied. 
                指数组元素复制长度
     1 package test;
     2 
     3 import java.util.Arrays;
     4 
     5 public class Test {
     6     public static void main(String[] args) {
     7         int[] source = {1,2,3,4,5};
     8         int[] dest = {10,9,8,7,6,5,4,3,2,1};
     9         
    10         System.arraycopy(source,0,dest,2,3);
    11         System.out.println(Arrays.toString(dest));
    12     }
    13 }
    示例代码
    1 [10, 9, 1, 2, 3, 5, 4, 3, 2, 1]
    运行结果

    
    
    2、四种方式之总结
    第一种方式得到的两个数组是两个不同的对象,用“==”比较结果一定是false;但用equals()方法比较可以是true。
     1 package test;
     2 
     3 import java.util.Arrays;
     4 
     5 public class Test {
     6   public static void main(String[] args) {
     7     int[] a = {1,2,4,6};
     8     int length = a.length;
     9     int[] b = new int[length];
    10 
    11     for (int i = 0; i < length; i++) {
    12       b[i]=a[i];
    13     }
    14 
    15   System.out.println(Arrays.toString(a));
    16   System.out.println(Arrays.toString(b));
    17 
    18   System.out.println(a.toString());
    19   System.out.println(b.toString());
    20   System.out.println("a==b:"+(a == b));
    21   System.out.println("Arrays.equals(a,b):"+Arrays.equals(a, b));
    22   }
    23 }
    示例代码
    1 [1, 2, 4, 6]
    2 [1, 2, 4, 6]
    3 [I@3654919e
    4 [I@6a2437ef
    5 a==b:false
    6 Arrays.equals(a,b):true
    运行结果

    第二种方式得到的两个数组其实就是一个对象,无论用 “==”还是 equals() 方法比较,结果都是true。

    第三种方式得到的两个数组是两个不同的对象。
    第四种方式得到的两个数组也是两个不同的对象。
  • 相关阅读:
    PyQt信号传递的方法
    tensorflow 遇到的细节问题
    正则表达式的总结
    ImageFont与PIL
    pytorch源码解析-动态接口宏
    intel windows caffe加速
    cnn可视化 感受野(receptive field)可视化
    Ubuntu安装使用latex
    使用caffe训练mnist数据集
    caffe使用ctrl-c不能保存模型
  • 原文地址:https://www.cnblogs.com/Mike_Chang/p/6618599.html
Copyright © 2011-2022 走看看