欢迎光临
感受代码之美

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

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)
转载请注明来源:四个空格 » Java集合List.contains()方法的正确使用

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址