查找操作
查找操作的本质是查找元素的下标:
查找第一次出现的index, 如果找不到返回-1;
- /**
- * 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 {@code i} such that
- * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
- * or -1 if there is no such index.
- *
- * @param o element to search for
- * @return the index of the first occurrence of the specified element in
- * this list, or -1 if this list does not contain the element
- */
- public int indexOf(Object o) {
- int index = 0;
- if (o == null) {
- for (Node<E> x = first; x != null; x = x.next) {
- if (x.item == null)
- return index;
- index++;
- }
- } else {
- for (Node<E> x = first; x != null; x = x.next) {
- if (o.equals(x.item))
- return index;
- index++;
- }
- }
- return -1;
- }
复制代码
查找最后一次出现的index, 如果找不到返回-1;
- /**
- * Returns the index of the last occurrence of the specified element
- * in this list, or -1 if this list does not contain the element.
- * More formally, returns the highest index {@code i} such that
- * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
- * or -1 if there is no such index.
- *
- * @param o element to search for
- * @return the index of the last occurrence of the specified element in
- * this list, or -1 if this list does not contain the element
- */
- public int lastIndexOf(Object o) {
- int index = size;
- if (o == null) {
- for (Node<E> x = last; x != null; x = x.prev) {
- index--;
- if (x.item == null)
- return index;
- }
- } else {
- for (Node<E> x = last; x != null; x = x.prev) {
- index--;
- if (o.equals(x.item))
- return index;
- }
- }
- return -1;
- }
复制代码
------
原文链接:https://pdai.tech/md/java/collection/java-collection-LinkedList.html
|