System.arraycopy方法的使用


package com.jiaozg.test;

import java.util.Arrays;

public class SystemArraycopyTest {
/**
* 从指定源数组中复制一个数组,复制从指定的位置开始,

*到目标数组的指定位置结束

*/
public static void main(String [] args) {
// 此方位为native方法。
// public static native void arraycopy(
// Object src, int srcPos, Object dest, int destPos, int length);
int[] ids = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(ids)); // [1, 2, 3, 4, 5]

//测试自我复制
//把从索引0开始的2个数字复制到索引为3的位置上
System.arraycopy(ids, 0, ids, 3, 2);
System.out.println(Arrays.toString(ids)); // [1, 2, 3, 1, 2]

//测试复制到别的数组上
//将数据的索引1开始的3个数据复制到目标的索引为0的位置上

int[] ids2 = new int[6];

System.arraycopy(ids, 1, ids2, 0, 3);
System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]

//此功能要求
//源的起始位置+长度不能超过末尾
//目标起始位置+长度不能超过末尾
//且所有的参数不能为负数
try {
System.arraycopy(ids, 0, ids2, 0, ids.length + 1);
} catch (IndexOutOfBoundsException ex) {
// 发生越界异常,数据不会改变System.out.println("拷贝发生异常:数据越界。");
}
System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]

//如果是类型转换问题
Object[] o1 = { 1, 2, 3, 4.5, 6.7 };
Integer[] o2 = new Integer[5];
System.out.println(Arrays.toString(o2)); // [null, null, null, null, null]

try {
System.arraycopy(o1, 0, o2, 0, o1.length);
} catch (ArrayStoreException ex) {
// 发生存储转换,部分成功的数据会被复制过去
System.out.println("拷贝发生异常:数据转换错误,无法存储。");
}

// 从结果看,前面3个可以复制的数据已经被存储了。剩下的则没有
System.out.println(Arrays.toString(o2)); // [1, 2, 3, null, null]

}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值