`

jdk1.5 System.arraycopy与jdk1.6 中Arrays.copyOf()&Arrays.copyOfRange()

    博客分类:
  • java
 
阅读更多

在JDK1.5的类System类中有方法

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

    标题上的这两上方法是JDK1.6新增的方法,这两个方法并没有用什么其它更奇妙的技巧,还是用的System.arraycopy(),只是在一定程度上减轻了程序员的工作,处理了一些常可能发生的错误。

    如:

    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;
    }

 

    public static byte[] copyOfRange(byte[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        byte[] copy = new byte[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics