码迷,mamicode.com
首页 > 其他好文 > 详细

Arrays.copyof

时间:2014-10-10 00:37:31      阅读:891      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   java   sp   div   on   

 public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

首先new一个新数组 然后copy过去 return这个新数组

int[] strArray = new int[] {1,2,3,4};
int[] copyArray=Arrays.copyOf(strArray,2);

结果copyArray就是1,2

int[] strArray = new int[] {1,2,3,4};
int[] copyArray=Arrays.copyOf(strArray,10);

结果1 2 3 4 0 0 0 0 0 0 

不会报错 因为最后的数组总是按后面那个newLength规定的新数组来说 

 

 

用System.arraycopy:

int[] strArray = new int[] {1,2,3,4};
        int[] copyArray = new int[4];
        System.arraycopy(strArray, 0, copyArray, 0, 5);

直接报错:java.lang.ArrayIndexOutOfBoundsException

如果把最后的5改成3

copyArray :1 2 3 0 

 

Arrays.copyof

标签:style   blog   color   io   ar   java   sp   div   on   

原文地址:http://www.cnblogs.com/sweetculiji/p/4014546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!