Why should we use an intermediate variable for @SuppressWarnings ("unchecked")?

Good afternoon everyone

I was wondering what is the reason 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; } } 

but

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

- syntax / compiler error?

What is the reason we should use an intermediate variable for @SuppressWarnings("unchecked") ?

+6
source share
3 answers

the @SuppressWarnings("unchecked") is applied to the sphere of action of declaration and assignment immediately after. This can be assigned to a scope or to a variable by setting a variable.
In the first example, it is applied to a local variable. In the second example, you are trying to apply it when assigning a field that has already been declared.

See that this also does not 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 does not affect the 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 to a variable in its entirety. It was applied to assignment + declaration (for variables) or throughout the method area when applied to the method.

+5
source

Because you can only annotate:

  • Classes
  • Methods
  • Variables
  • Parameters
  • packages

You cannot annotate expressions or statements.

+5
source

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 caveat is that @SuppressWarnings goes to the method rather than the line of code in b() because the suppression takes place when assigning a field, rather than assigning a local variable

+1
source

Source: https://habr.com/ru/post/907291/


All Articles