代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

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

  •  12
  • Cheok Yan Cheng  · 技术社区  · 14 年前

    Suspicious call to java.util.Collection.contains
    Expected type T, actual type Object
    

    我能知道那是什么意思吗?

    List Collection 班级 contains

    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);
        }
    

    集合类中的代码段

    /**
     * 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);
    

    /**
     * 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);
    
    2 回复  |  直到 14 年前
        1
  •  14
  •   dpsthree    14 年前

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

        2
  •  0
  •   josefx    14 年前

    用对象而不是泛型类型调用contains方法可能是编程错误。由于代码仍然有效,编译器将只显示一个警告。

    List<Long> l = new ArrayList<Long>();
    l.add(1l);
    l.contains(1);
    

    代码有效,但总是返回false。通常由包含接受对象而不是泛型类型隐藏的错误,因此编译器仅限于警告。

    由于有传递对象的有效用例,您应该能够使用@SuppressWarnings()注释来隐藏此警告(仅当您知道自己在做什么时才可以这样做)。