解讀ArrayList中的indexOf(Object o)方法

源碼如下:

    /**
     * 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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;
    }

可以看出,方法中首先判斷了傳入的對象是否爲空,如果爲空的話,會去遍歷尋找數組中爲空的對象,使用==的方式。

因爲空對象不能使用equals方法,而且判斷對象相等又不能使用==方法,因此找空對象時需要另外使用==的方式遍歷尋找。

結果就是分別判斷分別查找。

找到對應的對象以後,返回對象當前的下標

找不到對象的情況,返回-1.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章