Search code examples
javasuppress-warnings

Why do we have to use an intermediary variable for @SuppressWarnings("unchecked")?


Good afternoon all,

I was wondering what's the reason that

public class test<T> {
    T[] backing_array;

    public void a(int initial_capacity) {
        @SuppressWarnings("unchecked")
        T[] backing_array = (T[]) new Object[initial_capacity];
        this.backing_array = backing_array;
    }
}

is valid but

public class test<T> {
    T[] backing_array;

    public void b(int initial_capacity) {
        @SuppressWarnings("unchecked")
        this.backing_array = (T[]) new Object[initial_capacity];
    }
}

is a syntax/compiler error?

What's the reason that we have to use an intermediary variable for @SuppressWarnings("unchecked") ?


Solution

  • the @SuppressWarnings("unchecked") is applied on the scope of the declaration and assignment right after it. It can be assigned to functions' scope, or a specific variable's assignment.
    In your first example, it is applied on the local variable. In the 2nd example, you're trying to apply it on an assignment of a field that was already declared.

    See that this also doesn't compile:

    public class Test<T> {
    
        public void a(int initial_capacity) {
            T[] backing_array;
            @SuppressWarnings("unchecked")
            backing_array = (T[]) new Object[initial_capacity];
        }
    }
    

    and this has no effect on warnings:

    public class Test<T> {
    
        public void a(int initial_capacity) {
            @SuppressWarnings("unchecked")
            T[] backing_array;
            backing_array = (T[]) new Object[initial_capacity];
        }
    }
    

    In short, SuppressWarnings cannot be applied on a variable's throughout its scope. It's applied on an assignment+decleration (for variables) or on the entire method's scope when applied on a method.