0

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)
1

1 Answer 1

3

The statement @SuppressWarnings("unchecked") is misplaced. Move it above the constructor like this:

@SuppressWarnings("unchecked")
public Array(int L, int H) {
    this.array =  (T[]) (new Object[H- L+1]);
    this.l = L;
    this.h = H;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.