数组的Java复制部分 [英] Java copy section of array
本文介绍了数组的Java复制部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以复制数组的一部分(不是arraylist)并从中创建一个新数组?
Is there a method that will copy a section of an array(not arraylist) and make a new array from it?
Example:
[1,2,3,4,5]
,然后创建
[1,2,3]
是否有任何一行/方法可以做到这一点?
Are there any one line/methods that will do this?
推荐答案
这是与Java 1.4兼容的1.5衬套:
Here's a java 1.4 compatible 1.5-liner:
int[] array = { 1, 2, 3, 4, 5 };
int size = 3;
int[] part = new int[size];
System.arraycopy(array, 0, part, 0, size);
您可以在一行中执行此操作,但是不会引用结果。
You could do this in one line, but you wouldn't have a reference to the result.
要制作单线,可以将其重构为一种方法:
To make a one-liner, you could refactor this into a method:
private static int[] partArray(int[] array, int size) {
int[] part = new int[size];
System.arraycopy(array, 0, part, 0, size);
return part;
}
然后像这样调用:
int[] part = partArray(array, 3);
这篇关于数组的Java复制部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文