Java数组子 [英] Java array substring
问题描述
如何创建/实例化一个数组等于另一个数组,其中子的大小是未知的子串:
INT N; //一定数量的衍生别的地方的String [] = GRP元素[I],以元素[I + N]。
使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange%28T%5B%5D,%20int,%20int%29\"><$c$c>Arrays.copyOfRange$c$c>:
公共静态&LT; T&GT; T [] copyOfRange(T []原创,
从int,
诠释到)
复制指定的范围内
指定数组转换成一个新的数组。该
该范围的初始索引(从
)必须
0之间撒谎,original.length
,
包括的。在值原[从]
被放置到的初始元件
副本(除非从==
或
original.length从==来
)。值
从在随后的元件
原始数组被放入
在副本的后续元素。该
该范围的最后索引(到
),这
必须大于或等于从,
可能比original.length
更大,
在这种情况下,空被放置在所有的
复制索引为元素
大于或等于
original.length - 从
。的长度
返回的数组将是来 - 从
所得数组是完全
同一类原始数组。
块引用>在您的情况:
的String [] = GRP Arrays.copyOfRange(元素,I,I + N);
How can I create/instantiate an array to be equal to the substring of another array, where the size of the substring is unknown:
int n; //some number derived somewhere else String[] grp = elements[i] to elements[i+n];
解决方案Use
Arrays.copyOfRange
:public static <T> T[] copyOfRange(T[] original, int from, int to)
Copies the specified range of the specified array into a new array. The initial index of the range (
from
) must lie between zero andoriginal.length
, inclusive. The value atoriginal[from]
is placed into the initial element of the copy (unlessfrom == original.length
orfrom == to
). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to
), which must be greater than or equal to from, may be greater thanoriginal.length
, in which case null is placed in all elements of the copy whose index is greater than or equal tooriginal.length - from
. The length of the returned array will beto - from
.The resulting array is of exactly the same class as the original array.
In your case:
String[] grp = Arrays.copyOfRange(elements, i, i + n);
这篇关于Java数组子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!