Explanation of indexOf and lastIndexOf in Java AbstractList

Source code display

The source code of indexOf

    public int indexOf(Object o) {
    
    
        ListIterator<E> it = listIterator();
        if (o==null) {
    
    
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
    
    
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

lastIndexOf source code

 public int lastIndexOf(Object o) {
    
    
        ListIterator<E> it = listIterator(size());
        if (o==null) {
    
    
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
    
    
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }

indexOf principle

The first sentence first generates an iterator, which belongs to the ListIterator class, and chooses it instead of the ordinary Iterator Reason: ordinary Iterator can only traverse forward, and ListIterator has a previous parameter, which can be like LinkedList, it can be forward, or it can be directed to back.
After that, the if statement confirms whether the object is empty. If it is empty, it traverses forward and returns the total number of current List elements. If it is not empty, it returns exactly the location of the element. If it is not satisfied, it returns - 1.

lastIndexOf principle

The principle is the same as indexOf, the difference is that lastIndexOf traverses forward and returns the nth position from the bottom

Guess you like

Origin blog.csdn.net/deepdarkfan/article/details/100140834