Java集合List.contains()方法的正确使用

洼地云 tuoyidashi.png

java.util.Collection.contains(Object o)使用equals()方法判断对象是否存在,因此对于List集合,如果判断元素为String类型则可以直接使用,否则需要重写对象的equals方法才能正确判断。

源码如下:

 /**
     * 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
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

References

  1. [Java基础]ArrayList的contains方法,你用对了吗?
  2. java List集合中contains方法总是返回false
  3. boolean contains(Object o)
赞(0)
未经允许禁止转载:优米格 » Java集合List.contains()方法的正确使用

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册