public void expand(???, int number) {
array = java.util.Arrays.copyOf(array, array.length + number);
}
In "???", I want to accept any array regardless of type. Does the solution lie in Generic types?
public void expand(???, int number) {
array = java.util.Arrays.copyOf(array, array.length + number);
}
In "???", I want to accept any array regardless of type. Does the solution lie in Generic types?
If by "any array" you mean both an array of objects (e.g. String[]
) and an array of primitives (e.g. int[]
), then generics won't help you, and your only option is to take an Object
and verify it's an array.
public void expand(Object array, int number) {
if (! array.getClass().isArray())
throw new IllegalArgumentException("Not an array");
int arrayLen = Array.getLength(array);
// Sample methods for accessing array
Class<?> arrayValueClass = array.getClass().getComponentType(); // E.g. int.TYPE
int firstInt = Array.getInt(array, 0); // Assumes array is int[]
Object firstVal = Array.get(array, 0); // Always works. Primitives are boxed
}
Update
But, since you just want a convenience method for calling copyOf
, your best solution is to implement 10 versions of expand
, one for each version of copyOf
, less if you don't need support for all primitive array types:
public <T> T[] expand(T[] array, int number) {
return Arrays.copyOf(array, array.length + number);
}
public int[] expand(int[] array, int number) {
return Arrays.copyOf(array, array.length + number);
}
public double[] expand(double[] array, int number) {
return Arrays.copyOf(array, array.length + number);
}
// and so on...
Integer[] array = {1,2,3};
array = expand(array, 10);
System.out.println(array.length);
public <T> T[] expand(T[] array, int number) {
array = java.util.Arrays.copyOf(array, array.length + number);
return array;
}