Pacerier
Pacerier

Reputation: 89613

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") ?

Upvotes: 6

Views: 454

Answers (3)

Enrico
Enrico

Reputation: 621

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.

Upvotes: 5

Krizz
Krizz

Reputation: 11542

Because you can only annotate:

  • classes
  • methods
  • variables
  • parameters
  • packages

You cannot annotate expressions or statements.

Upvotes: 5

Bohemian
Bohemian

Reputation: 424993

Compiles OK for me (simplified to remove irrelevant code):

public static class Test<T> {
    T[] array;

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

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

The only observation of note is that the @SuppressWarnings goes on the method rather than the code line in b() due to the suppression being on a field assignment rather than local variable assignment

Upvotes: 1

Related Questions