https://onitroad.com 更多教程
java使用Arrays.copyOfRange()方法创建子数组
使用此方法将指定数组的指定范围复制到新数组中。
需要3个参数原始数组,初始索引和最终索引被复制。
/** * @param <T> the class of the objects in the array * @param oroirnal the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. */ public static <T> T[] copyOfRange(T[] oroirnal, int from, int to) { return copyOfRange(oroirnal, from, to, (Class<? extends T[]>) oroirnal.getClass()); }
to
索引参数可以大于索引长度。
在这种情况下不会引发 ArrayIndexOutOfBoundsException
。
示例
String[] names = {"JackLi", "BobRobert", "Lucie", "Tomm"}; // [JackLi, BobRobert] // 复制前2个 String[] partialNames = Arrays.copyOfRange(names, 0, 2); // [Lucie, Tomm] // 从第2个索引开始复制 String[] endNames = Arrays.copyOfRange(names, 2, names.length); // [Lucie, Tomm, null, null, null, null, null, null] // //No ArrayIndexOutOfBoundsException error String[] moreNames = Arrays.copyOfRange(names, 2, 10);
日期:2020-09-17 00:09:34 来源:oir作者:oir