Java – why do we have to use an intermediate variable (“unchecked”) for @ suppresswarnings?

Good afternoon, everyone,

I wonder why

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;
    }
}

It works, 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 it a syntax / compiler error?

Why do we have to use intermediate variables for @ suppresswarnings ("unchecked")?

Solution

@Suppresswarnings ("unchecked") will be applied in the scope after the declaration and job It can be assigned to the scope of a function or the assignment of a specific variable

You cannot compile when you see this:

public class Test<T> {

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

This has no effect on the warning:

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 to a wide range of variables When applied to a method, it applies to assignment removal (for variables) or the scope of the entire method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>