Search code examples
javaunchecked

Does the placement of @SuppressWarnings("unchecked") matter?


I had used @SuppressWarnings("unchecked") like:

class SomeClass {
  public static void main(String [] args) {
    Vector v = new Vector();
    @SuppressWarnings("unchecked")
    v.addElement(new Integer(1_000_000));
    // ...        

On compilation using javac version 8.0, I got the following errors:

error: <identifier> expected
        v.addElement(new Integer(1_000_000));

with the caret (^) pointing at the opening bracket of addElement method and one more error message complaining missing semicolon(;). The second message showed the caret near the closing bracket of addElement.

However, when I moved the @SuppressWarnings("unchecked") above the class SomeClass{, line, as in:

@SuppressWarnings("unchecked")
class SomeClass {

both the error messages disappeared automagically. This baffled me to any end. Is the positioning of @SuppressWarnings("unchecked") so critical?


Solution

  • You must not place annotations like @SuppressWarnings("unchecked") on a statement but only on a declaration.

    That's why the compiler does not understand the first variant:

    @SuppressWarnings("unchecked")
    v.addElement(new Integer(1_000_000));
    

    It's just illegal there and the compiler won't understand it.

    You could put it on the method instead, if you want to reduce the scope:

    @SuppressWarnings("unchecked")
    public static void main(String [] args) {
        Vector v = new Vector();
        v.addElement(new Integer(1_000_000));
    

    Thus, only warnings for the main method will be ignored, but not for the whole class.

    You can even put it on the variable declaration, but never on a statement:

    @SuppressWarnings("unchecked")
    Vector v = new Vector();
    

    However, as GhostCat has pointed out, in this case it is probably better to just generify the vector instead of ignoring warnings.