解读ArrayList中的indexOf(Object o)方法 2022-03-28 15:12 209阅读 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; } 可以看出,方法中首先判断了传入的对象是否为空,如果为空的话,会去遍历寻找数组中为空的对象,使用==的方式。 因为空对象不能使用equals方法,而且判断对象相等又不能使用==方法,因此找空对象时需要另外使用==的方式遍历寻找。 结果就是分别判断分别查找。 找到对应的对象以后,返回**对象当前的下标**。 找不到对象的情况,返回**-1**.
相关 ArrayList源码解读 1、概述 ArrayList是Java集合中使用比较多的,继承AbstractList,实现List接口。内部维护一个Object类型的数组elementData.允许n r囧r小猫/ 2022年10月14日 13:53/ 0 赞/ 73 阅读
相关 ArrayList源码解读 ArrayList源码解读 读前须知 源码 读前须知 这两个方法在源码中频繁使用,所以一定要先深刻理解 /数组扩容,原来数组的 喜欢ヅ旅行/ 2022年10月02日 04:48/ 0 赞/ 79 阅读
相关 ArrayList中remove方法的注意事项 少罗嗦,先看代码 public class ListRemove { public static void main(String[] args) 分手后的思念是犯贱/ 2022年05月21日 22:10/ 0 赞/ 128 阅读
相关 ArrayList源码解读 ArrayList继承了AbstractList类记忆实现了List接口,使用数组保存元素 public class ArrayList<E> extends Abs 悠悠/ 2022年04月11日 09:25/ 0 赞/ 88 阅读
相关 解读ArrayList中的indexOf(Object o)方法 源码如下: / Returns the index of the first occurrence of the specified elemen 小鱼儿/ 2022年03月28日 15:12/ 0 赞/ 210 阅读
相关 解读ArrayList中的grow(int minCapacity)方法 查看源码: / Increases the capacity to ensure that it can hold at least the 谁借莪1个温暖的怀抱¢/ 2022年03月28日 14:12/ 0 赞/ 272 阅读
相关 解读ArrayList中的add和remove方法 1. public boolean add(E e) / Appends the specified element to the end 港控/mmm°/ 2022年03月27日 03:08/ 0 赞/ 270 阅读
相关 ArrayList源码解读之remove(Object o)和remve(int index) 文章目录 ArrayList源码解读之remove(Object o)和remve(int index) 样例 remove(Object 亦凉/ 2022年02月27日 12:14/ 0 赞/ 138 阅读
相关 java——ArrayList中contains()方法中的疑问 问题引子: ist students=newArrayList(); students.add(newStudent("20160800612")); System.ou 浅浅的花香味﹌/ 2022年01月20日 07:25/ 0 赞/ 157 阅读
相关 谨用ArrayList中的subList方法 0、subList方法api: Parameters: fromIndex low endpoint (inclusive) of the subList 柔情只为你懂/ 2021年05月12日 11:49/ 0 赞/ 384 阅读
还没有评论,来说两句吧...