【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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容