Arrays.copyOfRange方法
- Arrays.copyOfRange方法源码,本质是调用了System.arraycopy方法
* @param original the array from which a range is to be copied 原数组
* @param from the initial index of the range to be copied, inclusive 从下标为from的元素开始拷贝,包括该元素
* @param to the final index of the range to be copied, exclusive。截至到下标为to的元素,不包括该元素
public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; }
- 需要注意的事项
1. 如果 from > to 会抛出 IllegalArgumentException异常
//代码 int[] a=new int[]{1,2,3}; System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,0))); //结果 Exception in thread "main" java.lang.IllegalArgumentException: 1 > 0
at java.base/java.util.Arrays.copyOfRange(Arrays.java:4101)
at test.test.main(test.java:11)
2. from > to ,会复制原数组下标区间为 [ from,to )范围内的元素
//代码
int[] a=new int[]{1,2,3};
System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,3)));
//结果
[2,3]
3. from = to ,会返回空数组
//代码
int[] a=new int[]{1,2,3};
System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,1)));
//结果
[]
4. to > 数组总长度,超出的部分会补0
//代码
int[] a=new int[]{1,2,3};
System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,5)));
//结果
[2, 3, 0, 0]
分类:
java基础
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现