Java基础Android进阶之路Android开发

【ArrayList源码】indexOf源码及使用

2019-07-13  本文已影响26人  秀叶寒冬

1 ArrayList的indexOf方法

ArrayList的indexOf源码如下:

/**
     * 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.
     * 返回指定元素在列表中第一次出现的索引,如果该列表不包含该元素,则返回-1。
     */
    public int indexOf(Object o) {
        if (o == null) {//#1
            for (int i = 0; i < size; i++)//#2
                if (elementData[i]==null)//#3
                    return i;//#4
        } else {//#5
            for (int i = 0; i < size; i++)//#6
                if (o.equals(elementData[i]))//#7
                    return i;//#8
        }
        return -1;//#9
    }

2 indexOf使用示例

        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(4);
        list.add(3);
        System.out.println(list.indexOf(3));
        
        List<String>list1 = new ArrayList<>();
        list1.add("ni");
        list1.add("wo");
        System.out.println(list1.indexOf("wo"));

输出:

2
1
上一篇 下一篇

猜你喜欢

热点阅读