Consider this code:
final public class Array<T> implements Iterable<T> {
private T[] array;
private int l;
private int h;
public Array(int L, int H) {
@SuppressWarnings("unchecked")
this.array = (T[]) (new Object[H- L+1]);
this.l = L;
this.h = H;
}
}
It fails to compile on my machine with the following error:
Array.java:21: error: illegal start of type
this.array = (T[]) (new Object[H- L+1]);
^
Array.java:21: error: ';' expected
this.array = (T[]) (new Object[H- L+1]);
^
2 errors
The syntax-checker/linter that is available in VSCode even complains about the following:
[Java] Syntax error, insert "enum Identifier" to complete EnumHeaderName
[Java] Syntax error, insert "EnumBody" to complete BlockStatements
after the @SupressWarnings statement.
However when I change the constructor to this:
final public class Array<T> implements Iterable<T> {
private T[] array;
private int l;
private int h;
public Array(int L, int H) {
@SuppressWarnings("unchecked")
final a = (T[]) (new Object[H- L+1]);
this.array = a;
this.l = L;
this.h = H;
}
}
It works as expected.
My question is:
What can I not assign the generic array directly to my local field ? Is this a compiler bug ?
I am using the following java version on an up-to-date arch linux install.
$ java -showversion
openjdk version "1.8.0_172"
OpenJDK Runtime Environment (build 1.8.0_172-b11)
OpenJDK 64-Bit Server VM (build 25.172-b11, mixed mode)