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

对着背影说爱祢 提交于 2019-12-08 19:32:23

问题


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


回答1:


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.




回答2:


Because you can only annotate:

  • classes
  • methods
  • variables
  • parameters
  • packages

You cannot annotate expressions or statements.




回答3:


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



来源:https://stackoverflow.com/questions/9076083/why-do-we-have-to-use-an-intermediary-variable-for-suppresswarningsunchecked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!