System.arrayCopy 的作用

下面是 System.arrayCopy的源代码声明 :

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代码解释:
  Object src : 原数组
   int srcPos : 从元数据的起始位置开始
  Object dest : 目标数组
  int destPos : 目标数组的开始起始位置
  int length  : 要copy的数组的长度

比如 :我们有一个数组数据 byte[] srcBytes = new byte[]{2,4,0,0,0,0,0,10,15,50}; // 源数组
byte[] destBytes = new byte[5]; // 目标数组
我们使用System.arraycopy进行转换(copy)
System.arrayCopy(srcBytes,0,destBytes ,0,5)
上面这段代码就是 : 创建一个一维空数组,数组的总长度为 12位,然后将srcBytes源数组中 从0位 到 第5位之间的数值 copy 到 destBytes目标数组中,在目标数组的第0位开始放置.
那么这行代码的运行效果应该是 2,4,0,0,0

java中应用举例

java.util.concurrent中的CopyOnWriteArrayList类中的addAll()方法

/**
     * Appends all of the elements in the specified collection to the end
     * of this list, in the order that they are returned by the specified
     * collection's iterator.
     *
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     * @see #add(Object)
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
            ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
        if (cs.length == 0)
            return false;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            if (len == 0 && cs.getClass() == Object[].class)
                setArray(cs);
            else {
                Object[] newElements = Arrays.copyOf(elements, len + cs.length);
                System.arraycopy(cs, 0, newElements, len, cs.length);
                setArray(newElements);
            }
            return true;
        } finally {
            lock.unlock();
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 数组是一种特殊的对象,保存零个或多个基本类型或引用类型的值。这些值是数组的元素,是通过所在位置或索引引用的无名变量...
    郭艺宾阅读 519评论 0 1
  • DAY 01 JAVA简述 Java是由SUN公司在1995年推出的一门高级编程语言,是现今服务器端的首选编程语言...
    周书达阅读 1,015评论 0 0
  • 一. Java基础部分.................................................
    wy_sure阅读 3,835评论 0 11
  • 分析目的 接触了 java 两年,虽然在2015年阅读了一遍 Collection 接口下面的各种实现。但...
    超级小学生1阅读 416评论 1 2
  • 今天是什么日子 起床:7.10 就寝:11.50 天气:雨 心情:相对较好 任务清单 昨日完成的任务,最重要的三件...
    乌拉乌啦阅读 245评论 0 1