对java.util.Collection.contains的可疑调用

Che*_*eng 13 java

我从NetBeans IDE收到以下警告.

Suspicious call to java.util.Collection.contains
Expected type T, actual type Object
Run Code Online (Sandbox Code Playgroud)

我知道这意味着什么吗?

这对我来说没有意义.Both ListCollectionclass的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);
    }
Run Code Online (Sandbox Code Playgroud)

Collection类的代码片段

/**
 * 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&nbsp;?&nbsp;e==null&nbsp;:&nbsp;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);
Run Code Online (Sandbox Code Playgroud)

List类的代码片段

/**
 * 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&nbsp;?&nbsp;e==null&nbsp;:&nbsp;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);
Run Code Online (Sandbox Code Playgroud)

dps*_*ree 13

在对list.contains的调用中,您将对象与类型T进行比较.将类型T转换为类型T应解决警告.

  • 不会将`Object`声明更改为`T`是更好的选择吗? (3认同)
  • @Bobby:实际上,它是`Collection`接口中定义的抽象方法的实现.因此,我们必须坚持宣言. (3认同)
  • 签名看起来像这样的唯一原因是:boolean contains(Object o)不使用T就是向后兼容。在Java 5之前,没有泛型,并且可以用错误类型的对象调用“ contains”,并且总是获取“ false”。由于这些程序仍应像以前一样编译和工作,因此签名需要一个Object。但是,大多数IDE都会警告您有关通用Collection中错误的数据类型。 (2认同)