我从NetBeans IDE收到以下警告。
Suspicious call to java.util.Collection.contains
Expected type T, actual type Object
我可以知道这意味着什么吗?
这对我没有意义。 List
和Collection
类的contains
方法都使用Object作为方法参数。
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);
}
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);
列表类的代码段
/**
* 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);
答案 0 :(得分:12)
在对list.contains的调用中,您将对象与类型T进行比较。将类型T转换为类型T可解决警告。
答案 1 :(得分:0)
使用Object而不是泛型类型调用contains方法可能是编程错误。由于代码仍然有效,编译器只会显示警告。
需要此警告的示例:
List<Long> l = new ArrayList<Long>();
l.add(1l);
l.contains(1);
代码有效但总是返回false。通常由包含接受对象而不是泛型类型隐藏的错误,因此编译器仅限于警告。
由于存在传递对象的有效用例,因此您应该能够使用@SuppressWarnings()注释来隐藏此警告(仅在您知道自己在做什么时才执行此操作)。