Inner classes also have access to generic type of its outer class. Lets say that we have
class Foo<T> {
class Point {
float x, y;
T value;
T getValue(){
return value;
}
}
}
When you create instance of Foo
like
Foo<String> f = new Foo<>();
we can create instance of its inner class based on its outer instance like
Point p = f.new Point();
// or
//Foo<String>.Point p = f.new Point
// if we are creating it for instance outside of Foo class
and compiler will know that p.getValue()
returns String, so it can lets us use p.getValue().charAt(0)
.
Now problem is that generic type can't be used in any part of array type, which means that we can't use:
T[size]
.
Foo<T>[size]
- or not even
Foo<T>.Point[size]
The last example seems to be your case because
Point[] points = new Point[3];
is equivalent of
Point[] points = new Foo<T>.Point[3];
// Foo<T> is type of outer instance on which you are invoking new
You have few options to solve this problem.
You can explicitly say that you don't want to use generic type by writing
Point[] points = new Foo.Point[3];// we got rid of <T>
but don't do that because raw types are evil.
Better solution is to avoid arrays and use Collection which support generics like List<Point>
.
List<Point> points = new ArrayList<>();
But probably best solution is to simply get rid of dependency of T
from outer class Foo
. This can be achieved by making your inner class static, which means it will not require instance of its outer class, so it will not need to know about which generic type is used by it.
So you can simply use
static class Point {
float x, y;
}
and now
Point[] points = new Point[3];
will compile fine.