数组的拷贝

1.循环遍历

public class Test {

    public static void main(String[] args) {
      String [] str={"abc","def","ghi"};
        Object[] objects = Test.demo1(str);
        for (Object obj:objects
             ) {
            System.out.println(obj);
        }
    }

    /**
     * 数组遍历赋值
     * @param obj 要拷贝的数组
     * @return 返回拷贝后的新数组
     */
    public static Object[] demo1(Object [] obj){
      Object [] temp = new Object[obj.length];
        for (int i = 0; i <obj.length ; i++) {
            temp[i]=obj[i];
        }
        return temp;
    }

2.Array.copy

其方法底层还是调用了

System.arraycopy(original, 0, copy, 0,
                 Math.min(original.length, newLength));

  public static <T> T[] demo2(T[] obj) {
        T[] copy = Arrays.copyOf(obj, obj.length);
        return copy;
    }

3.System.arraycopy(src,srcPos,dest,desPos,length)

* @param      src      the source array.
* @param      srcPos   starting position in the source array.
* @param      dest     the destination array.
* @param      destPos  starting position in the destination data.
* @param      length   the number of array elements to be copied.
 public static Object [] demo3(Object [] obj) {
        Object[] copy = new Object[obj.length];
        System.arraycopy(obj, 0, copy, 0, obj.length);
        return  copy;
    }

4.clone

  public static Object [] demo4(Object [] obj){
        Object [] copy = obj.clone();
        return copy;
    }

clone是浅拷贝

只是复制引用

例:

public static void test(){
        String[] str = {"abc", "def", "ghi"};
        String[] clone = str.clone();
        str[0]="test";
        System.out.println(clone[0]);

        StringBuilder sb1 = new StringBuilder("abc");
        StringBuilder sb2 = new StringBuilder("abc");
        StringBuilder sb3 = new StringBuilder("abc");
        StringBuilder sb4 = new StringBuilder("abc");
        StringBuilder [] sb = {sb1,sb2,sb3,sb4};
        StringBuilder[] clone1 = sb.clone();
        sb1.append("test");
        System.out.println(clone1[0]);
    }

结果:

String 是不可改变的,重新赋值时,会在常量池中新创建一个字符串。

clone只是复制了引用,只 是赋值了str数组中的引用,当str[0]的引用改变,clone的引用不变,结果还是“abc”,sb数组证明了这一点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值