I have a strange problem using Generics in Java. Generics are quite new to me, but I think I understand the basics.
Please have a look at this piece of code:
private void drawQuadtreeBoxes_helper(QuadTree<?> node) {
if (node == null)
return;
Vector3 min = node.bbox.min;
Vector3 max = node.bbox.max;
// Draw the boxes (...)
if (node.hasChildren()) {
Array<QuadTree<?>> children = node.getChildren(); // ERROR HERE
for (QuadTree<?> child : children) {
drawQuadtreeBoxes_helper(child);
}
}
}
Because the type of objects stored inside the quadtree-structure is not relevant for this method, I use a wildcard for the method signature, so that this method can be applied to all kinds of QuadTree’s.
The method getChildren() returns the four childs of the node, stored inside the collection-class called Array (implementation of Array). I am sure the return type of getChildren() is indeed Array<QuadTree<?>> (even Eclipse says so inside the tooltip), but I still get an error on this line, telling me:
cannot convert from Array<QuadTree<capture#6-of ?>> to Array<QuadTree<?>>
Here comes the fun part: When I ask Eclipse for suggestions how to solve this, this is one of the suggestions:
Change type of 'children' to 'Array<QuadTree<?>>'
But it already is of this type! It get’s better: When I click on this suggestion, Eclipse changes this line to:
Array<?> children = node.getChildren();
Of course, this destroys all the following code.
What the heck is going on here? Could someone enlighten me, please?
The problem is the method doesn’t know it’s the same
QuadTree<?>(the?could refer to different types in the same call).The solution is to “type” the method, which locks in
QuadTree<?>(and therefore?) to be the same type throughout the method.?still means “anything”, but it now the same “anything”.