快捷搜索: 王者荣耀 脱发

【ArrayList源码】indexOf源码及使用

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
    }
    #1判断指定对象类型是否为null,如果为空进行#2;如果不为空,进行#5。 #2进行for循环,size指的是当前ArrayList大小 #3判断ArrayList中元素是否为空,elementData是ArrayList里的元素。如果为空进行#4. #4返回i,说明在ArrayList中找到了为null的位置。 #5如果指定对象(indexOf传入的参数)不为空,则进行#6; #6进行for循环。 #7判断elementData数组中是否存在与指定元素相等的元素,如果有,则进行#8。这里的equals与指定值类型和列表存储值类型有关。 #8返回与指定元素相等的索引位置。 #9如果没有找到,则返回-1。

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
经验分享 程序员 微信小程序 职场和发展