返回与索引数组大小相同的数组以及原始数组的类,该类包含由相应索引选择的原始数组的元素。
/** * Copyright (c) 2010 Martin Geisse * * This file is distributed under the terms of the MIT license. */ import java.lang.reflect.Array;/** 时代Java - nowjava.com 提供 **/ public class Main{ /** * Returns an array of the same size as the indexArray and the class of * the originalArray which contains the elements of the original array * selected by the corresponding indices. * @param <T> the static type of the original array * @param originalArray the original array form which objects are selected * @param indexArray the array of indices used to select elements of the * original array * @return Returns the selected elements. */ public static <T> T[] selectByIndexArray(T[] originalArray, int[] indexArray) { Object[] untypedSelectedElements = (Object[]) Array.newInstance( originalArray.getClass().getComponentType(), indexArray.length); T[] selectedElements = ArrayUtil .<T> unsafeCastArray(untypedSelectedElements); for (int i = 0; i < indexArray.length; i++) { selectedElements[i] = originalArray[indexArray[i]]; } return selectedElements; } /** * Returns an array of the same size as the indexArray and the class of * the originalArray which contains the elements of the original array * selected by the corresponding indices. * @param originalArray the original array form which objects are selected * @param indexArray the array of indices used to select elements of the * original array * @return Returns the selected elements. */ public static int[] selectByIndexArray(int[] originalArray, int[] indexArray) { int[] selectedElements = (int[]) Array.newInstance(Integer.TYPE, indexArray.length);/*时 代 J a v a - N o w J a v a . c o m 提供*/ for (int i = 0; i < indexArray.length; i++) { selectedElements[i] = originalArray[indexArray[i]]; } return selectedElements; }