Assuming your Box
will always hold arrays then the simplest solution is to make your type parameter T
be the element type instead of the array type (e.g., Integer
instead of Integer[]
) then make the private variable be of type T[]
rather than T
. Then Box
will always have easy access to the array elements, and can also conveniently use any java.util.Arrays
methods such as toString
on it:
public class Box<T> {
private T[] t;
public Box(T[] t) { this.t = t; }
public void getTheT() {
System.out.println(t[0]); // access individual elements
System.out.println(java.util.Arrays.toString(t)); // print the lot
}
}
public class App {
public static void main(String[] args) {
Integer[] Arr = { 2, 3, 4 };
Box<Integer> i = new Box<>(Arr); // not Box<Integer[]> any more
i.getTheT();
}
}
The catch is that since Java generics do not currently work with primitive types, you will have to put up with the overhead of object/boxed types (e.g., Integer
instead of int
).
If you want to keep T
as the array type itself (perhaps because you want to allow Box<int[]>
, since Box<int>
is not possible) then it gets more tricky. In that case you can't simply use [
...]
.
You can use the methods of java.util.reflect.Array
to get access to arbitrary arrays' elements no matter what variable type they are stored in. This gives basic get and set access, but the methods are somewhat slow (fine for debugging but not for much else):
public class Box<T> {
private T t;
public Box(T t) { this.t = t; }
public void getTheT() {
// print all array elements
for (int i = 0, len = java.lang.reflect.Array.getLength(t); i < len; i++) {
System.out.println(java.lang.reflect.Array.get(t, i));
}
}
}
public class App {
public static void main(String[] args) {
int[] Arr = { 2, 3, 4 };
Box<int[]> i = new Box<>(Arr); // primitive array element type!
i.getTheT();
}
}
Unfortunately there is currently no nice, performant way in Java to write code that can work with elements of all arrays, regardless of their types. Instead, such code has to be written nine times as you see the methods of java.util.Arrays
are. That's once for element type Object
(and everything that extends Object
), and then once each for the primitive element types (boolean
, byte
, short
, char
, int
, long
, float
, double
).