I am getting the following warning from my NetBeans IDE.
Suspicious call to java.util.Collection.contains Expected type T, actual type Object
May I know what does that means?
This doesn't make sense to me. Both List
and Collection
class's contains
method, are using Object as their method parameter.
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * * @author yan-cheng.cheok */ public abstract class AbstractCollection<T> implements Collection<T> { protected List<T> list = new ArrayList<T>(); public boolean contains(Object o) { // Suspicious call to java.util.Collection.contains // Expected type T, actual type Object return list.contains(o); }
Code snippet from Collection class
/** * Returns <tt>true</tt> if this collection contains the specified element. * More formally, returns <tt>true</tt> if and only if this collection * contains at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * * @param o element whose presence in this collection is to be tested * @return <tt>true</tt> if this collection contains the specified * element * @throws ClassCastException if the type of the specified element * is incompatible with this collection (optional) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements (optional) */ boolean contains(Object o);
Code snippet from List class
/** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional) * @throws NullPointerException if the specified element is null and this * list does not permit null elements (optional) */ boolean contains(Object o);
In the call to list.contains you are comparing an object to a type T. Casting o to type T should resolve your warning.
Calling the contains method with an Object instead of the generic type may be a programming error. Since the code is still valid the compiler will only show a warning.
An example why this warning is necessary:
List<Long> l = new ArrayList<Long>(); l.add(1l); l.contains(1);
The code is valid but would always return false. An error that is normally hidden by contains accepting object instead of a generic type, so the compiler is limited to warnings.
Since there are valid use cases for passing an object, you should be able to use a @SuppressWarnings() annotation to hide this warning (only do this if you know what you are doing).
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