zoukankan      html  css  js  c++  java
  • Java数组的复制Arrays.copyOf()、System.arraycopy()、nums.clone()

    public static native void arraycopy(Object src,  int  srcPos,  
                                            Object dest, int destPos,  
                                            int length); 
    

     arraycopy是个本地方法,无返回值。

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {  
            T[] copy = ((Object)newType == (Object)Object[].class)  
                ? (T[]) new Object[newLength]  
                : (T[]) Array.newInstance(newType.getComponentType(), newLength);  
            System.arraycopy(original, 0, copy, 0,  
                             Math.min(original.length, newLength));  
            return copy;  
        }  
    public static <T> T[] copyOf(T[] original, int newLength) {  
        return (T[]) copyOf(original, newLength, original.getClass());  
    }  
    

    copyOf()底层调用arraycopy,不过可以直接返回一个数组,代码更加简短,只是自定义数组长度的能力更差了。

    最简单的方法直接调用num2=num.clone()即可返回,该方法默认是一个浅拷贝,但是对于int和String型数组,相当于深拷贝(String[] str={"1","123"},str[0]="2"并没有改变"1"的内容,而是新建了一个String,将str[0]指向这个String而已)

  • 相关阅读:
    VMware Ubuntu安装详细过程
    Ubuntu16.04下安装sublime text3
    Linux ubuntu下svn的命令使用指南
    Ubuntu 安装Phpstorm+汉化+激活
    ubuntu下安装php openssl扩展
    Unbuntu三行命令安装Google
    ①Python简史
    单向链表操作
    特殊文件(下)
    特殊文件(上)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/5774889.html
Copyright © 2011-2022 走看看