1. 程式人生 > >java中ArrayList的contains(obj)和indexOf(obj)方法的呼叫順序

java中ArrayList的contains(obj)和indexOf(obj)方法的呼叫順序

1.結論

ArrayList的contains(obj)和indexOf(obj)方法都是obj與陣列中的每個元素進行比較,而不是陣列中的每個元素和obj比較

2.官方原始碼

java.util.ArrayList<E>
 /**
     * 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;
    }

3.理解容易引發的錯誤

contains(obj)和indexOf(obj)都呼叫了obj的equals方法,如果錯誤地認為是陣列中的每個元素和obj比較,

在equals()方法裡面就會搞不清是哪個物件

在工作中遇到這個問題,特此記錄