【Java X 原始碼剖析】Collection的原始碼分析-JDK1.8-仍在更新

TypantK發表於2019-03-13

Collection介面下的結構

 

目錄

Set

HashSet

LinkedHashSet(父類HashSet,底層Map為LinkedHashMap)

TreeSet(依賴TreeMap)

ConcurrentSkipListSet

 

List-Queue

PriorityQueue(預設小頂堆)

①public boolean offer(E e) / public boolean add(E e)

List

LinkedList

addAll(int index, Collection c):

①public boolean add(E e) 

②public boolean remove(Object o)

ArrayList:動態擴容

①public boolean add(E e)

②public E set(int index, E element) 

③public int indexOf(Object o) :可以查詢null元素,意味ArrayList可以存放null

④public E get(int index)

⑤public E remove(int index):刪除時會移動大量元素

Vector(過時的類,每個方法都有Synchronized)[可以存null]

Vector屬性

建構函式

 

Stack

 

 


Set

HashSet

一些屬性

*所有的鍵都有同一個值PRESENT

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    //用作所有鍵的值,因為HashSet中只存鍵不存值
    private static final Object PRESENT = new Object();
}

方法都是呼叫HashMap中的方法,不再重複


    public int size() {
        return map.size();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }


    public boolean contains(Object o) {
        return map.containsKey(o);
    }


    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

    public void clear() {
        map.clear();
    }

 

 

LinkedHashSet(父類HashSet,底層Map為LinkedHashMap)

一些屬性

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

    //沒有屬性,都是呼叫父類的屬性

}

建構函式

呼叫父類的建構函式,使其底層實現變成LinkedHashMap

//兩個方法呼叫同一個父類的構造方法
public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

public LinkedHashSet() {
        super(16, .75f, true);
    }

public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

 

 

TreeSet(依賴TreeMap)

一些屬性

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

    // Dummy value to associate with an Object in the backing Map
    //同樣的套路:所有鍵的value都是PRESENT
    private static final Object PRESENT = new Object();
}

 

建構函式

    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

    //還有別的構造方法就不一一列舉了

 

*底層方法實現同TreeMap

    public int size() {
        return m.size();
    }

    public boolean isEmpty() {
        return m.isEmpty();
    }

    public boolean contains(Object o) {
        return m.containsKey(o);
    }


    public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }


    public boolean remove(Object o) {
        return m.remove(o)==PRESENT;
    }


    public void clear() {
        m.clear();
    }

 

 

 

ConcurrentSkipListSet

 

一些屬性

 

建構函式

 

 

 

 

List-Queue

PriorityQueue(預設小頂堆)

①public boolean offer(E e) / public boolean add(E e)

    public boolean add(E e) {
        return offer(e);
    }

    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

    /**
     * Increases the capacity of the array.
     *
     * @param minCapacity the desired minimum capacity
     */
    //陣列容量已經不滿足下標了,遂擴容
    private void grow(int minCapacity) {
        int oldCapacity = queue.length;

        // Double size if small; else grow by 50%
        //如果原本容量小於64就變2n+2;否則變1.5n
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // overflow-conscious code
        //陣列最大值 or Integer_MAX_VALUE
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        queue = Arrays.copyOf(queue, newCapacity);
    }

    private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

    //有比較器(預設小頂堆) k為x在陣列中的下標
    @SuppressWarnings("unchecked")
    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            //父親結點陣列下標
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            //比父親大,小頂堆,就不用在往上移了
            if (comparator.compare(x, (E) e) >= 0)
                break;
            //暫時不用賦值x,最後迴圈出去再賦值
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

    //Queue沒有比較器,使用插入的物件的比較器
    @SuppressWarnings("unchecked")
    private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

 

 

 

List

LinkedList

*可以存null,不支援隨機讀取,可以不用考慮擴容

 

一些屬性

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;
}
private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

 

建構函式

    public LinkedList() {

    }
    
    //呼叫無參構造器,然後將集合c中元素新增到LinkedList中
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }


    public boolean addAll(Collection<? extends E> c) {
        //預設從尾結點開始插入集合中資料
        return addAll(size, c);
    }

    //返回false表示集合中沒有資料,返回true表示新增成功
    public boolean addAll(int index, Collection<? extends E> c) {
        //可以檢查是否超過size或者小於0(不同於ArrayList只能檢查是否超過size)
        checkPositionIndex(index);
        
        //熟悉的套路:將集合轉換成Object型別陣列
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            //直接從尾結點插入
            succ = null;
            pred = last;
        } else {
            //將集合中資料從第index個結點後開始插入
            //獲取第index個node(如果小於size/2,從頭找;如果大於size/2,從尾找)
            succ = node(index);
            pred = succ.prev;
        }

        //依次插入到連結串列尾
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    //新增操作或者迭代器時使用
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

addAll(int index, Collection<? extends E> c):

 

根據index獲取到第index個結點方法

Node<E> node(int index) {
        // assert isElementIndex(index);

        //分為左半和右半,提高查詢效率
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

 

①public boolean add(E e) 

public boolean add(E e) {
        linkLast(e);
        return true;
    }

/**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        //如果連結串列原本為空(last/first都為空,上面為last賦值,下面為first賦值,指向同一節點)
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

 

②public boolean remove(Object o)

public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Unlinks non-null node x.
     */
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        //1.前驅結點空-->刪除的是頭結點
        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        //2.後繼結點為空-->刪除的是尾結點
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        //3.結點值設定為空
        x.item = null;

        size--;
        modCount++;
        return element;
    }

 

 

 

ArrayList:動態擴容

*可以插入null元素,還可以任意隨機讀取,不好的地方就是刪除時需要移動大量元素

 

一些屬性

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
     /**
     * The size of the ArrayList (the number of elements it contains).
     * 實際元素數量
     * @serial
     */
    private int size;
   
     /**
     * Default initial capacity.
     * 預設初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    //用來賦值給elementData元素陣列
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    //當使用無參構造器,用來賦值給elementData元素陣列
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     * 元素陣列
     */
    //存的是Object,get的時候會偷偷轉型
    transient Object[] elementData; // non-private to simplify nested class access
}

 

建構函式

public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {    //初始容量>0
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {    //初始容量為0,返回空物件陣列
            this.elementData = EMPTY_ELEMENTDATA;
        } else {    //初始容量<0,丟擲非法初始容量異常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        //未賦值引數,會給elementData設定為空陣列
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        //將傳遞進來的集合轉換成陣列
        elementData = c.toArray();
        //如果陣列不為空
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //轉換的陣列可能沒轉換成Object型別陣列
            if (elementData.getClass() != Object[].class)
                //採用複製的方式,將元素複製進elementData
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            //如果集合為空,就傳遞空陣列給元素陣列
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

 

①public boolean add(E e)

/**
     * Appends the specified element to the end of this list.
     * 將指定元素新增到此列表的末尾
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;    
        return true;
    }

//minCapacity 指的是所需的最小容量
private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

private static int calculateCapacity(Object[] elementData, int minCapacity) {
        //判斷是否為空陣列(無參構造器構造的ArrayList)
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }


private void ensureExplicitCapacity(int minCapacity) {
        //熟悉的操作次數+1
        modCount++;

        // overflow-conscious code
        //溢位
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

/**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;

        //新容量為舊容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);

        //新容量小於引數指定容量
        //也就是空陣列插入時,直接將容量從0擴充成10,否則會變成1,這樣新陣列一開始插入的時候很容易觸發擴容
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;

        //新容量超過了陣列能接受的最大容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);

        // minCapacity is usually close to size, so this is a win:
        //拷貝+擴容
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

 

*為了防止ArrayList在初期插入資料時頻繁擴容,所以對於沒有設定長度限制的,第一次插入資料就給予了預設長度(10)

 

 

②public E set(int index, E element) 

/**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    //將列表中指定元素替換
    public E set(int index, E element) {
        //檢查index合法性
        rangeCheck(index);

        //三部曲:得到舊值,替換舊值,返回舊值
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

/**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    //不檢查負數,似乎交給陣列類來進行檢查了?如果是負數丟擲ArrayIndexOutOfBoundsException,和下面這個異常不一樣
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

 

③public int indexOf(Object o) :可以查詢null元素,意味ArrayList可以存放null

/**
     * 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.
     */
    //返回第一個o的陣列下標,如果不存在就返回-1
    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++)

                //null就用不了equals方法了
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

 

④public E get(int index)

/**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    //返回指定位置的元素
    public E get(int index) {
        //index範圍檢查
        rangeCheck(index);

        return elementData(index);
    }

隱藏了向下轉型的細節(將Object轉成了E)

@SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

 

⑤public E remove(int index):刪除時會移動大量元素

public E remove(int index) {
        rangeCheck(index);

        modCount++;    //和新增一樣,操作次數+1
        E oldValue = elementData(index);

        //需要移動的元素個數
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //真正意義上的刪除,將要刪除的元素設定為null,這樣才gc,而不是僅僅改一個size
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

通過本地陣列複製函式來進行移動元素

    /*            需要被複制的陣列
     * @param      src      the source array.
     *            從哪個元素開始複製
     * @param      srcPos   starting position in the source array.
     *            需要被複制到哪個陣列
     * @param      dest     the destination array.
     *            從新陣列的哪個位置賦值
     * @param      destPos  starting position in the destination data.
     *            需要複製的數
     * @param      length   the number of array elements to be copied.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

 

Vector(過時的類,每個方法都有Synchronized)[可以存null]

首先說一下Vector是否執行緒安全的結論:

Vector 和 ArrayList 實現了同一介面 List, 但所有的 Vector 的方法都具有 synchronized 關鍵修飾,也就單一操作還是執行緒安全的。但對於複合操作,Vector 仍然需要進行同步處理

複合操作:

if (!vector.contains(element)) 
    vector.add(element); 
    ...
}

在執行contains()和add()方法時,可以保證沒有方法在使用Vector物件,都是原子性操作(Synchronized作用)。

但是執行完contains(),無法保證下一個執行的就是add()

要想實現複合操作的執行緒安全,還得用Synchronized再加一個鎖,鎖住Vector物件

Synchronized(vector){
    boolean b = vector.contains(element);
    if(!b)vector.add(element);
}

這也就是Vector被棄用原因明明一個鎖就夠,還得兩個鎖才能解決執行緒安全問題

 

Vector屬性

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     */
    //Vector底層實現陣列
    protected Object[] elementData;

    /**
     * The number of valid components in this {@code Vector} object.
     * Components {@code elementData[0]} through
     * {@code elementData[elementCount-1]} are the actual items.
     *
     * @serial
     */
    //實際元素個數
    protected int elementCount;

    /**
     * The amount by which the capacity of the vector is automatically
     * incremented when its size becomes greater than its capacity.  If
     * the capacity increment is less than or equal to zero, the capacity
     * of the vector is doubled each time it needs to grow.
     *
     * @serial
     */
    //如果擴容未指定此引數,Vector就增長為原來兩倍
    //如果擴容指定此引數(capacitryIncrement>0),就增加capacityIncrement這麼多容量
    protected int capacityIncrement;
}

 

建構函式

    //下面兩個構造器的最終構造器
    //設定初始引數和增長容量大小,以及新建陣列空間
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    /**
     * Constructs an empty vector with the specified initial capacity and
     * with its capacity increment equal to zero.
     *
     * @param   initialCapacity   the initial capacity of the vector
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    //指定陣列空間大小,沒有指定增加容量大小
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * Constructs an empty vector so that its internal data array
     * has size {@code 10} and its standard capacity increment is
     * zero.
     */
    //陣列空間為10,沒有設定增加容量大小
    public Vector() {
        this(10);
    }

    /**
     * Constructs a vector containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this
     *       vector
     * @throws NullPointerException if the specified collection is null
     * @since   1.2
     */
    //還是熟悉的套路:c.toArray可能不是Object物件陣列;不是的話就手動轉(Arrays.copyOf)
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

Vector的方法實現還是比較簡單的,就不一一列出了。

 

Stack

Stack類的程式碼就只有這麼多,還是比較簡單的。

通過繼承Vector(陣列)來實現,主要是pop()

public
class Stack<E> extends Vector<E> {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

    //直接新增到陣列
    public E push(E item) {
        addElement(item);

        return item;
    }


    //很好理解,拿陣列大小最後一個元素
    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();

        //檢查len-1合法性,將最後一個元素置為空(gc),數量-1
        removeElementAt(len - 1);

        return obj;
    }


    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }


    public boolean empty() {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack.
     * If the object <tt>o</tt> occurs as an item in this stack, this
     * method returns the distance from the top of the stack of the
     * occurrence nearest the top of the stack; the topmost item on the
     * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
     * method is used to compare <tt>o</tt> to the
     * items in this stack.
     *
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value <code>-1</code>
     *          indicates that the object is not on the stack.
     */
    //返回距離棧頂的距離
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }


}

 

相關文章