I have a generic class, called Node<E>
and I'm trying to define a static method that will return an array of objects of this type. I understand that Java does not allow the creation of generic type arrays within a class so we have to create an Object array and pass our generic types through the object.
For an example of the code, let's define it as:
public static Object[] returnArray() {
Object[] output;
//code which adds Node<E> to output
return output;
When I implement this code though, I am not able to:
- perform this class's methods on the objects within the array as they are of type
Object
- If
Node<E>
had a method.getVal()
the following code results in an error:Object[] nodes = Node.returnArray(head); nodes[0].getVal();
- If
- cast and return method array to a
Node<E>[]
array, even when explicit of the type.Node<Integer>[] nodes = (Node<Integer>[]) Node.returnArray(head);
So the only way I am currently accessing the methods of each node is by assigning them to a variable by casting:
Object[] nodes = Node.returnArray(head);
Node<Integer> returned1 = (Node<Integer>) nodes[0];
Node<Integer> returned2 = (Node<Integer>) nodes[1];
But you can see how redundant it gets as the code grows. Is there a better way to access generic objects passed to an array?