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")
?
Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
If you choose to put @SuppressWarnings("rawtypes") at the method level, Eclipse will suppress all raw-types warnings inside that method. If we compile same code without @SuprressWarnings, using javac compiler it will show the following hint: $ javac RawType. java Note: RawType. java uses unchecked or unsafe operations.
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.
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.
Because you can only annotate:
You cannot annotate expressions or statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With