【java】【java Collection】LinkedList

来源:互联网 发布:java上机编程题面试 编辑:程序博客网 时间:2024/05/16 06:41


源代码;

package java.util;import java.util.function.Consumer;/** * Doubly-linked list implementation of the  List and  Deque interfaces. (实现队列和双端队列)  * Implements all optional list operations, and permits all elements (including null). * * All of the operations perform as could be expected for a doubly-linked list.   * Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. * * Note that this implementation is not synchronized.(非同步) * If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.   *(A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.)   *This is typically accomplished by synchronizing on some object that naturally encapsulates the list. * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method.  This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> *   List list = Collections.synchronizedList(new LinkedList(...));</pre> * * <p>The iterators returned by this class's {@code iterator} and * {@code listIterator} methods are <i>fail-fast</i>: if the list is * structurally modified at any time after the iterator is created, in * any way except through the Iterator's own {@code remove} or * {@code add} methods, the iterator will throw a {@link * ConcurrentModificationException}.  Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than * risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification.  Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness:   <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * *//*序列化补充:父类实现序列化 子类都是能够被序列化;如果父类没有实现序列化,子类实现Serializable接口,子类也是能够序列化的static和transient两类对象无法实现序列化*/public class LinkedList<E>    extends AbstractSequentialList<E>    implements List<E>, Deque<E>, Cloneable, java.io.Serializable{       //LinkedList中元素个数    transient int size = 0;    //内部节点类    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;        }    }    //找到如何设置头结点和尾节点的代码    /**     * 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;    public LinkedList() {    }    public LinkedList(Collection<? extends E> c) {        this();//调用上面的无参构造函数        addAll(c);    }    private boolean isPositionIndex(int index) {        return index >= 0 && index <= size;    }    private String outOfBoundsMsg(int index) {        return "Index: "+index+", Size: "+size;    }    private void checkPositionIndex(int index) {        if (!isPositionIndex(index))            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));    }    private boolean isElementIndex(int index) {        return index >= 0 && index < size;    }    //获取索引在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 addAll(Collection<? extends E> c) {        return addAll(size, c);    }    public boolean addAll(int index, Collection<? extends E> c) {        checkPositionIndex(index);        Object[] a = c.toArray();        int numNew = a.length;        if (numNew == 0)            return false;  //如果没有元素需要添加  就直接返回false        Node<E> pred, succ;//succ表示index对应位置的元素   pred代表其前一个元素        if (index == size) {//插入的位置是最后一个元素下一位            succ = null;            pred = last;        } else {            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)//pred如果为null 说明原本的链表就为空                first = newNode;//则将新生成的节点作为first节点            else                pred.next = newNode;//否则将刚生成的节点作为pred的后继节点            pred = newNode;//循环插入节点        }        //如果succ为空 代表是在双向链表的末尾开始插入元素 那么其新插入的最后一个节点要设置成last节点        if (succ == null) {            last = pred;        } else {            //否则要将index节点和新插入的节点之间构成双向箭头            pred.next = succ;            succ.prev = pred;        }        size += numNew;//元素个数增加        modCount++;//迭代器修改次数        return true;    }    //将节点设置成first节点    private void linkFirst(E e) {        final Node<E> f = first;        final Node<E> newNode = new Node<>(null, e, f);        first = newNode;        if (f == null)//如果原本LinkedList为空 那么last和first都是指向同一个位置的            last = newNode;        else            f.prev = newNode;//将原来的first节点前引用指向newnode  后引用在new Node<>(null, e, f)就已经设置好了 所以就不需要写了        size++;        modCount++;    }    //将节点设置成为尾节点    void linkLast(E e) {        final Node<E> l = last;        final Node<E> newNode = new Node<>(l, e, null);        last = newNode;        if (l == null)//如果原LinkedList为空  则first和last都是需要指向newNode            first = newNode;        else            l.next = newNode;//双向操作        size++;        modCount++;    }    //Inserts element e before non-null Node succ.     void linkBefore(E e, Node<E> succ) {        // assert succ != null;        final Node<E> pred = succ.prev;        final Node<E> newNode = new Node<>(pred, e, succ);        succ.prev = newNode;//顺序不要弄反  这里因为已经将succ.prev给了pred  所以顺序反了也是不会影响最后的效果的        if (pred == null)            first = newNode;//头结点之前插入节点        else            pred.next = newNode;        size++;        modCount++;    }    //去掉第一个节点  返回其节点值    private E unlinkFirst(Node<E> f) {        // assert f == first && f != null;   //指定节点必须为first且first必须不为空        final E element = f.item;        final Node<E> next = f.next;        f.item = null;        f.next = null; // help GC        first = next;        if (next == null)//如果原本只有一个节点  那么last也就是需要设置成空            last = null;        else            next.prev = null;//否则原本first.next指向first引用        size--;//元素个数减一        modCount++;        return element;    }    //去掉尾节点    private E unlinkLast(Node<E> l) {        // assert l == last && l != null;        final E element = l.item;        final Node<E> prev = l.prev;        l.item = null;        l.prev = null; // help GC        last = prev;        if (prev == null)            first = null;//如果LinkedList原本就只有一个节点  则其首节点也必须设置为空        else            prev.next = null;        size--;        modCount++;        return element;    }    //去除指定节点    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.prev和next都为null  孤立的一个节点  first = next;  last = prev;  此时first和last都会null        //2.prev == null&&next!=null    设置头结点 加上去除原头结点和其下一个节点之间的关系                //尾节点        //3.prev != null &&next==null        //中间节点        if (prev == null) {  //如果要删除的节点是first节点            first = next;        } else {            prev.next = next;            x.prev = null;//help  gc        }        if (next == null) { //如果要删除的节点是last节点            last = prev;        } else {            next.prev = prev;            x.next = null;//help  gc        }        x.item = null;//help  gc        size--;        modCount++;        return element;    }    //返回首节点的元素值    public E getFirst() {        final Node<E> f = first;        if (f == null)            throw new NoSuchElementException();        return f.item;    }    //返回尾节点的元素值    public E getLast() {        final Node<E> l = last;        if (l == null)            throw new NoSuchElementException();        return l.item;    }    //移除首节点    public E removeFirst() {        final Node<E> f = first;        if (f == null)            throw new NoSuchElementException();        return unlinkFirst(f);    }   //移除尾节点    public E removeLast() {        final Node<E> l = last;        if (l == null)            throw new NoSuchElementException();        return unlinkLast(l);    }    //在first节点之前插入节点    public void addFirst(E e) {        linkFirst(e);    }    //在last插入节点    public void addLast(E e) {        linkLast(e);    }    //对象o需要判断是否为null    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;    }    public boolean contains(Object o) {        return indexOf(o) != -1;    }    // Returns the number of elements in this list.    public int size() {        return size;    }    //在LinkedList末尾插入元素    public boolean add(E e) {        linkLast(e);        return true;    }    //去除指定节点  第一次出现节点    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;    }    //清空LinkedList    public void clear() {        // Clearing all of the links between nodes is "unnecessary", but:        // - helps a generational GC if the discarded nodes inhabit        //   more than one generation        // - is sure to free memory even if there is a reachable Iterator        for (Node<E> x = first; x != null; ) {            Node<E> next = x.next;            x.item = null;            x.next = null;            x.prev = null;            x = next;        }        first = last = null;        size = 0;        modCount++;    }    private void checkElementIndex(int index) {        if (!isElementIndex(index))            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));    }    //返回节点值    public E get(int index) {        checkElementIndex(index);//确保下标在范围内        return node(index).item;    }    //设置节点的值    public E set(int index, E element) {        checkElementIndex(index);        Node<E> x = node(index);        E oldVal = x.item;        x.item = element;        return oldVal;    }    //插入节点 如果插入的位置是last后面一个位置  否则就是在index节点之前插入元素    public void add(int index, E element) {        checkPositionIndex(index);        if (index == size)            linkLast(element);        else            linkBefore(element, node(index));    }    //移除节点    public E remove(int index) {        checkElementIndex(index);        return unlink(node(index));    }    //分节点为null和不为null两种情况    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;    }    // Queue operations.    public E peek() {        final Node<E> f = first;        return (f == null) ? null : f.item;    }    public E element() {        return getFirst();    }        public E poll() {        final Node<E> f = first;        return (f == null) ? null : unlinkFirst(f);    }    public E remove() {        return removeFirst();    }        public boolean offer(E e) {        return add(e);    }    // Deque operations    public boolean offerFirst(E e) {        addFirst(e);        return true;    }    public boolean offerLast(E e) {        addLast(e);        return true;    }    public E peekFirst() {        final Node<E> f = first;        return (f == null) ? null : f.item;     }    public E peekLast() {        final Node<E> l = last;        return (l == null) ? null : l.item;    }    public E pollFirst() {        final Node<E> f = first;        return (f == null) ? null : unlinkFirst(f);    }    public E pollLast() {        final Node<E> l = last;        return (l == null) ? null : unlinkLast(l);    }    public void push(E e) {        addFirst(e);    }    public E pop() {        return removeFirst();    }        public boolean removeFirstOccurrence(Object o) {        return remove(o);    }    //从后往前遍历  删除第一次出现的节点值    public boolean removeLastOccurrence(Object o) {        if (o == null) {            for (Node<E> x = last; x != null; x = x.prev) {                if (x.item == null) {                    unlink(x);                    return true;                }            }        } else {            for (Node<E> x = last; x != null; x = x.prev) {                if (o.equals(x.item)) {                    unlink(x);                    return true;                }            }        }        return false;    }    public ListIterator<E> listIterator(int index) {        checkPositionIndex(index);        return new ListItr(index);    }    private class ListItr implements ListIterator<E> {        private Node<E> lastReturned;        private Node<E> next;        private int nextIndex;        private int expectedModCount = modCount;        ListItr(int index) {            // assert isPositionIndex(index);            next = (index == size) ? null : node(index);            nextIndex = index;        }        public boolean hasNext() {            return nextIndex < size;        }        public E next() {            checkForComodification();            if (!hasNext())                throw new NoSuchElementException();            lastReturned = next;            next = next.next;            nextIndex++;            return lastReturned.item;        }        public boolean hasPrevious() {            return nextIndex > 0;        }        public E previous() {            checkForComodification();            if (!hasPrevious())                throw new NoSuchElementException();            lastReturned = next = (next == null) ? last : next.prev;            nextIndex--;            return lastReturned.item;        }        public int nextIndex() {            return nextIndex;        }        public int previousIndex() {            return nextIndex - 1;        }        public void remove() {            checkForComodification();            if (lastReturned == null)                throw new IllegalStateException();            Node<E> lastNext = lastReturned.next;            unlink(lastReturned);            if (next == lastReturned)                next = lastNext;            else                nextIndex--;            lastReturned = null;            expectedModCount++;        }        public void set(E e) {            if (lastReturned == null)                throw new IllegalStateException();            checkForComodification();            lastReturned.item = e;        }        public void add(E e) {            checkForComodification();            lastReturned = null;            if (next == null)                linkLast(e);            else                linkBefore(e, next);            nextIndex++;            expectedModCount++;        }        public void forEachRemaining(Consumer<? super E> action) {            Objects.requireNonNull(action);            while (modCount == expectedModCount && nextIndex < size) {                action.accept(next.item);                lastReturned = next;                next = next.next;                nextIndex++;            }            checkForComodification();        }        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }        /**     * @since 1.6     */    public Iterator<E> descendingIterator() {        return new DescendingIterator();    }    /**     * Adapter to provide descending iterators via ListItr.previous     */    private class DescendingIterator implements Iterator<E> {        private final ListItr itr = new ListItr(size());        public boolean hasNext() {            return itr.hasPrevious();        }        public E next() {            return itr.previous();        }        public void remove() {            itr.remove();        }    }    /*        Object中的clone()         protected native Object clone() throws CloneNotSupportedException;         本地方法    */    @SuppressWarnings("unchecked")    private LinkedList<E> superClone() {        try {            return (LinkedList<E>) super.clone();        } catch (CloneNotSupportedException e) {            throw new InternalError(e);        }    }    public Object clone() {        LinkedList<E> clone = superClone();        // Put clone into "virgin" state        clone.first = clone.last = null;        clone.size = 0;        clone.modCount = 0;        // Initialize clone with our elements        for (Node<E> x = first; x != null; x = x.next)            clone.add(x.item);        return clone;    }        public Object[] toArray() {        Object[] result = new Object[size];        int i = 0;        for (Node<E> x = first; x != null; x = x.next)            result[i++] = x.item;        return result;    }    public <T> T[] toArray(T[] a) {        if (a.length < size)            a = (T[])java.lang.reflect.Array.newInstance(                                a.getClass().getComponentType(), size);        int i = 0;        Object[] result = a;        for (Node<E> x = first; x != null; x = x.next)            result[i++] = x.item;        if (a.length > size)            a[size] = null;        return a;    }    private static final long serialVersionUID = 876323262645176354L;    //Saves the state of this  LinkedList instance to a stream     private void writeObject(java.io.ObjectOutputStream s)        throws java.io.IOException {        // Write out any hidden serialization magic        s.defaultWriteObject();        // Write out size        s.writeInt(size);        // Write out all elements in the proper order.        for (Node<E> x = first; x != null; x = x.next)            s.writeObject(x.item);    }    //Reconstitutes this  LinkedList instance from a stream (that is, deserializes it).    @SuppressWarnings("unchecked")    private void readObject(java.io.ObjectInputStream s)        throws java.io.IOException, ClassNotFoundException {        // Read in any hidden serialization magic        s.defaultReadObject();        // Read in size        int size = s.readInt();        // Read in all elements in the proper order.        for (int i = 0; i < size; i++)            linkLast((E)s.readObject());    }    /**     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>     * and <em>fail-fast</em> {@link Spliterator} over the elements in this     * list.     *     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and     * {@link Spliterator#ORDERED}.  Overriding implementations should document     * the reporting of additional characteristic values.     *     * @implNote     * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}     * and implements {@code trySplit} to permit limited parallelism..     *     * @return a {@code Spliterator} over the elements in this list     * @since 1.8     */    @Override    public Spliterator<E> spliterator() {        return new LLSpliterator<E>(this, -1, 0);    }    /** A customized variant of Spliterators.IteratorSpliterator */    static final class LLSpliterator<E> implements Spliterator<E> {        static final int BATCH_UNIT = 1 << 10;  // batch array size increment        static final int MAX_BATCH = 1 << 25;  // max batch array size;        final LinkedList<E> list; // null OK unless traversed        Node<E> current;      // current node; null until initialized        int est;              // size estimate; -1 until first needed        int expectedModCount; // initialized when est set        int batch;            // batch size for splits        LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {            this.list = list;            this.est = est;            this.expectedModCount = expectedModCount;        }        final int getEst() {            int s; // force initialization            final LinkedList<E> lst;            if ((s = est) < 0) {                if ((lst = list) == null)                    s = est = 0;                else {                    expectedModCount = lst.modCount;                    current = lst.first;                    s = est = lst.size;                }            }            return s;        }        public long estimateSize() { return (long) getEst(); }        public Spliterator<E> trySplit() {            Node<E> p;            int s = getEst();            if (s > 1 && (p = current) != null) {                int n = batch + BATCH_UNIT;                if (n > s)                    n = s;                if (n > MAX_BATCH)                    n = MAX_BATCH;                Object[] a = new Object[n];                int j = 0;                do { a[j++] = p.item; } while ((p = p.next) != null && j < n);                current = p;                batch = j;                est = s - j;                return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);            }            return null;        }        public void forEachRemaining(Consumer<? super E> action) {            Node<E> p; int n;            if (action == null) throw new NullPointerException();            if ((n = getEst()) > 0 && (p = current) != null) {                current = null;                est = 0;                do {                    E e = p.item;                    p = p.next;                    action.accept(e);                } while (p != null && --n > 0);            }            if (list.modCount != expectedModCount)                throw new ConcurrentModificationException();        }        public boolean tryAdvance(Consumer<? super E> action) {            Node<E> p;            if (action == null) throw new NullPointerException();            if (getEst() > 0 && (p = current) != null) {                --est;                E e = p.item;                current = p.next;                action.accept(e);                if (list.modCount != expectedModCount)                    throw new ConcurrentModificationException();                return true;            }            return false;        }        public int characteristics() {            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;        }    }}


遍历方式

package Test.fast;import java.util.Iterator;import java.util.LinkedList;import java.util.NoSuchElementException;public class LinkedListThruTest {    public static void main(String[] args) {        // 通过Iterator遍历LinkedList        iteratorLinkedListThruIterator(getLinkedList()) ;        // 通过快速随机访问遍历LinkedList        iteratorLinkedListThruForeach(getLinkedList()) ;        // 通过for循环的变种来访问遍历LinkedList        iteratorThroughFor2(getLinkedList()) ;        // 通过PollFirst()遍历LinkedList        iteratorThroughPollFirst(getLinkedList()) ;        // 通过PollLast()遍历LinkedList        iteratorThroughPollLast(getLinkedList()) ;        // 通过removeFirst()遍历LinkedList        iteratorThroughRemoveFirst(getLinkedList()) ;        // 通过removeLast()遍历LinkedList        iteratorThroughRemoveLast(getLinkedList()) ;    }    private static LinkedList getLinkedList() {        LinkedList llist = new LinkedList();        for (int i=0; i<100000; i++)            llist.addLast(i);        return llist;    }    /**     * 通过快迭代器遍历LinkedList     */    private static void iteratorLinkedListThruIterator(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        for(Iterator iter = list.iterator(); iter.hasNext();)            iter.next();        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorLinkedListThruIterator:" + interval+" ms");    }    /**     * 通过快速随机访问遍历LinkedList     */    private static void iteratorLinkedListThruForeach(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        int size = list.size();        for (int i=0; i<size; i++) {            list.get(i);        }        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorLinkedListThruForeach:" + interval+" ms");    }    /**     * 通过另外一种for循环来遍历LinkedList     */    private static void iteratorThroughFor2(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        for (Integer integ:list)            ;        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorThroughFor2:" + interval+" ms");    }    /**     * 通过pollFirst()来遍历LinkedList     */    private static void iteratorThroughPollFirst(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        while(list.pollFirst() != null)            ;        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorThroughPollFirst:" + interval+" ms");    }    /**     * 通过pollLast()来遍历LinkedList     */    private static void iteratorThroughPollLast(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        while(list.pollLast() != null)            ;        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorThroughPollLast:" + interval+" ms");    }    /**     * 通过removeFirst()来遍历LinkedList     */    private static void iteratorThroughRemoveFirst(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        try {            while(list.removeFirst() != null)                ;        } catch (NoSuchElementException e) {        }        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorThroughRemoveFirst:" + interval+" ms");    }    /**     * 通过removeLast()来遍历LinkedList     */    private static void iteratorThroughRemoveLast(LinkedList<Integer> list) {        if (list == null)            return ;        // 记录开始时间        long start = System.currentTimeMillis();        try {            while(list.removeLast() != null)                ;        } catch (NoSuchElementException e) {        }        // 记录结束时间        long end = System.currentTimeMillis();        long interval = end - start;        System.out.println("iteratorThroughRemoveLast:" + interval+" ms");    }}


结果

iteratorLinkedListThruIterator:13 msiteratorLinkedListThruForeach:3759 msiteratorThroughFor2:4 msiteratorThroughPollFirst:3 msiteratorThroughPollLast:3 msiteratorThroughRemoveFirst:3 msiteratorThroughRemoveLast:4 ms

随机访问是最慢的


示例代码:


package Test.fast;import java.util.LinkedList;public class LinkedListTest {    public static void main(String[] args) {        // 测试LinkedList的API        testLinkedListAPIs() ;        // 将LinkedList当作 LIFO(后进先出)的堆栈        useLinkedListAsLIFO();        // 将LinkedList当作 FIFO(先进先出)的队列        useLinkedListAsFIFO();    }    /*     * 测试LinkedList中部分API     */    private static void testLinkedListAPIs() {        String val = null;        //LinkedList llist;        //llist.offer("10");        // 新建一个LinkedList        LinkedList llist = new LinkedList();        //---- 添加操作 ----        // 依次添加1,2,3        llist.add("1");        llist.add("2");        llist.add("3");        // 将“4”添加到第一个位置        llist.add(1, "4");        System.out.println("\nTest \"addFirst(), removeFirst(), getFirst()\"");        // (01) 将“10”添加到第一个位置。  失败的话,抛出异常!        llist.addFirst("10");        System.out.println("llist:"+llist);        // (02) 将第一个元素删除。        失败的话,抛出异常!        System.out.println("llist.removeFirst():"+llist.removeFirst());        System.out.println("llist:"+llist);        // (03) 获取第一个元素。          失败的话,抛出异常!        System.out.println("llist.getFirst():"+llist.getFirst());        System.out.println("\nTest \"offerFirst(), pollFirst(), peekFirst()\"");        // (01) 将“10”添加到第一个位置。  返回true。        llist.offerFirst("10");        System.out.println("llist:"+llist);        // (02) 将第一个元素删除。        失败的话,返回null。        System.out.println("llist.pollFirst():"+llist.pollFirst());        System.out.println("llist:"+llist);        // (03) 获取第一个元素。          失败的话,返回null。        System.out.println("llist.peekFirst():"+llist.peekFirst());        System.out.println("\nTest \"addLast(), removeLast(), getLast()\"");        // (01) 将“20”添加到最后一个位置。  失败的话,抛出异常!        llist.addLast("20");        System.out.println("llist:"+llist);        // (02) 将最后一个元素删除。        失败的话,抛出异常!        System.out.println("llist.removeLast():"+llist.removeLast());        System.out.println("llist:"+llist);        // (03) 获取最后一个元素。          失败的话,抛出异常!        System.out.println("llist.getLast():"+llist.getLast());        System.out.println("\nTest \"offerLast(), pollLast(), peekLast()\"");        // (01) 将“20”添加到第一个位置。  返回true。        llist.offerLast("20");        System.out.println("llist:"+llist);        // (02) 将第一个元素删除。        失败的话,返回null。        System.out.println("llist.pollLast():"+llist.pollLast());        System.out.println("llist:"+llist);        // (03) 获取第一个元素。          失败的话,返回null。        System.out.println("llist.peekLast():"+llist.peekLast());        // 将第3个元素设置300。不建议在LinkedList中使用此操作,因为效率低!        llist.set(2, "300");        // 获取第3个元素。不建议在LinkedList中使用此操作,因为效率低!        System.out.println("\nget(3):"+llist.get(2));        // ---- toArray(T[] a) ----        // 将LinkedList转行为数组        String[] arr = (String[])llist.toArray(new String[0]);        for (String str:arr)            System.out.println("str:"+str);        // 输出大小        System.out.println("size:"+llist.size());        // 清空LinkedList        llist.clear();        // 判断LinkedList是否为空        System.out.println("isEmpty():"+llist.isEmpty()+"\n");    }    /**     * 将LinkedList当作 LIFO(后进先出)的堆栈     */    private static void useLinkedListAsLIFO() {        System.out.println("\nuseLinkedListAsLIFO");        // 新建一个LinkedList        LinkedList stack = new LinkedList();        // 将1,2,3,4添加到堆栈中        stack.push("1");        stack.push("2");        stack.push("3");        stack.push("4");        // 打印“栈”        System.out.println("stack:"+stack);        // 删除“栈顶元素”        System.out.println("stack.pop():"+stack.pop());        // 取出“栈顶元素”        System.out.println("stack.peek():"+stack.peek());        // 打印“栈”        System.out.println("stack:"+stack);    }    /**     * 将LinkedList当作 FIFO(先进先出)的队列     */    private static void useLinkedListAsFIFO() {        System.out.println("\nuseLinkedListAsFIFO");        // 新建一个LinkedList        LinkedList queue = new LinkedList();        // 将10,20,30,40添加到队列。每次都是插入到末尾        queue.add("10");        queue.add("20");        queue.add("30");        queue.add("40");        // 打印“队列”        System.out.println("queue:"+queue);        // 删除(队列的第一个元素)        System.out.println("queue.remove():"+queue.remove());        // 读取(队列的第一个元素)        System.out.println("queue.element():"+queue.element());        // 打印“队列”        System.out.println("queue:"+queue);    }}


参考资料:

http://www.cnblogs.com/skywang12345/p/3308807.html

0 0
原创粉丝点击