Search code examples
javagenericssuppress-warnings

Why does @SuppressWarnings break my code?


Got this idea from this previous question.

How to create a generic array in Java?

Anyway, my code is like this:

public class Slice<E>
{
    private E[] data;
    public Slice(Class<E> elementType, int size)
    {
        //@SuppresWarnings({"unchecked"})
        data = (E[])Array.newInstance(elementType, size);
    }

}

I deleted the unnecessary stuff. This compiles fine when the suppress directive is commented out. When I uncomment it, I get

Error: <identifier> expected    
        data = (E[])Array.newInstance(elementType, size);
             ^

Any ideas? why would this be happening?


Solution

  • You cannot put an annotation there. It must go before the public keyword. And you've mistyped the annotation name as well: change SuppresWarnings to SuppressWarnings.

    EDIT: If you were using an IDE like Eclipse, you would typically use the auto-correction feature to insert the annotation. Naturally, it would be inserted in the right place and correctly spelled.