Java – why not simply disable unchecked warnings?
Developers often encounter "unchecked" warnings when interacting with non - Generic APIs Consider the following example:
import java.util.AbstractList; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class IterableNodeList<T extends Node> extends AbstractList<T> { private NodeList list; public IterableNodeList(NodeList list) { this.list = list; } public T get(int index) { return (T)this.list.item(index); } public int size() { return this.list.getLength(); } }
Of course, you can put effort into writing such a way: no warning: use the type parameter t on the class, use the constructor parameter class < T >, match the member variable and a cast () call
Alternatively, consider simply editing ide configuration and build scripts (such as Maven POM) to completely disable the compiler warning Now, if we do this, the code can remain as it is, but I'm sure there must be shortcomings However, I can't think of any reasonable and realistic examples
>This warning provides more value than "stick to @ suppresswarnings here, no other choice", and where > the code is actually different (and safer) from our behavior of ignoring (disabling) warnings
Can you think of such an example, or point out that another reason to disable these "unchecked" warnings around the world is a bad idea? Or is it actually a good idea?
UPDATE
The previous example did not actually give rise to a warning Some answers no longer make sense Sorry for the inconvenience
Solution
According to item 24 of effective java version 2, it is usually a bad idea to use @ suppresswarnings widely and frequently, especially if you apply this annotation to the whole class, because such warnings will show dangerous code that may lead to ClassCastException
However, in some cases, this may be useful, such as the toArray method implementation of ArrayList:
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type,but my contents: return (T[]) Arrays.copyOf(elementData,size,a.getClass()); System.arraycopy(elementData,a,size); if (a.length > size) a[size] = null; return a; }