As I understood your question, you could create a method that take a list of indexes as parameters.
For generic arrays, you'll need to use Array.newInstance and cast the resulting array to T[] (thanks and kudos for @Radiodef for pointing this out)
//for lists
static <T> List<T> buildList(List<T> original, int... indexes){
List<T> finalList = new ArrayList<>();
for(int index : indexes){
finalList.add(original.get(index));
}
return finalList;
}
//for arrays
static <T> T[] buildArray (T[] original, int... indexes){
@SuppressWarnings("unchecked")
T[] finalArray = (T[])Array.newInstance(original.getClass().getComponentType(), indexes.length);
for(int i = 0; i < indexes.length; i++){
finalArray[i] = original[indexes[i]];
}
return finalArray;
}
Few notes :
- For primitive arrays (like
int[] or double[]), you'll have to overload the methods, that's why I suggest you to use a List with generics instead.
- Indexes for arrays in Java are 0 based (starts from 0 to length-1)
- Don't forget to add additional checks for the method (valid index, original list or index not null)
- If you use a
LinkedList instead of an ArrayList, be aware that #get(int index) is an O(n) operation instead of O(1)
Example of usage :
public static void main(String[] args) {
Integer[] xArray = {-1, 10, 24, 7};
List<Integer> xList = Arrays.asList(-1, 10, 24, 7);
System.out.println(Arrays.toString(buildArray(xArray, 0, 2)));
System.out.println(buildList(xList, 0, 1, 3));
}
Which outputs:
[-1, 24]
[-1, 10, 7]
Rhave indices from1or from0? The arrays in Java start indices from0.