[JAVA set] collections list, javalinkedlist

Source: Internet
Author: User

[JAVA set] collections list, javalinkedlist

The following content is based on the jdk1.7.0 _ 79 source code;

What is shortlist?

List interface implementation, and provides some queue, stack, double-end queue operations;

Additional instructions on using list

Compared with ArrayList, the insert and delete operations on the shortlist are more efficient and the random access speed is slow;

It can be used as the data structure of stacks, queues, and double-end queues;

Non-synchronous, thread unsafe;

Like ArrayList and Vector, the internal iterator of the slow list has a "fast failure ";

Supports null elements, ordered elements, and repeated elements;

Classes inherited by the shortlist and the Implemented interfaces

The Iterable interface, Collection interface, List interface, Cloneable, java. io. description of the Serializable interface, AbstractCollection class, And AbstractList class. When introducing ArrayList, a rough description is provided, here we will mainly understand the Queue interface, Deque interface, AbstractSequentialList class, and shortlist class;

Queue Interface

The queue interface defines some basic queue operations,

Note that the following blue font methods (offer, poll, and peek) are preferred. The queue generally does not allow null elements, because we usually call the poll method to determine whether the queue is null, however, the queue list allows null elements. Therefore, when using the most queue Implementation of the queue list, the null element should not be inserted into the queue;

Boolean add (E e );

Insert Object e to the end of the queue, and return true if it is successful. If it fails (no space), an exception is thrown.IllegalStateException;

Boolean offer (E e );

Insert Object e to the end of the queue. true is returned for success, false is returned for failure (no space;

E remove ();

Gets and removes the queue Header element. If the queue is empty, a NoSuchElementException exception is thrown;

E poll ();

Gets and removes the queue Header element. If the queue is empty, null is returned;

E element ();

Retrieve but not remove the queue Header element. If the queue is empty, a NoSuchElementException exception is thrown;

E peek ();

Retrieve but not remove the queue Header element. If the queue is empty, null is returned;

For example, the Code for implementing a queue based on the queue list is as follows:

Package com. pickers. basis. col; import java. util. using list; import java. util. queue; public class LinkListTest {public static void main (String [] args) {Queue <Integer> Queue listqueue = new Queue list <Integer> (); // Queue listqueue. offer (3); initialize listqueue. offer (4); initialize listqueue. offer (2); initialize listqueue. offer (1); // departure Integer tmp; while (tmp = queue listqueue. poll ())! = Null) {System. out. println (tmp);} System. out. println (Bytes listqueue. peek ());}}
Deque Interface

The dual-end queue interface inherits the queue interface and supports queuing and queuing at both ends of the queue;

In addition to the methods defined in the Queue interface of the Collection interface, Deque also includes the following methods:

Void addFirst (E e );

Inserts Object e into the head of the dual-end queue. If the capacity is insufficientIllegalStateExceptionException;

Void addLast (E e );

Insert Object e to the end of the dual-end queue. If the capacity is insufficientIllegalStateExceptionException;

Boolean offerFirst (E e );

Insert Object e into the head of the double-end queue

Boolean offerLast (E e );

Insert Object e to the end of the double-end queue;

E removeFirst ();

Gets and removes the first element of the queue. The queue is empty and throwsNoSuchElementExceptionException;

E removeLast ();

Gets and removes the last element of the queue. The queue is empty and throwsNoSuchElementExceptionException;

E pollFirst ();

Obtain and remove the first element of the queue. If the queue is empty, null is returned;

E pollLast ();

Get and remove the last element of the queue. If the queue is empty, null is returned;

E getFirst ();

Gets the first element of the queue, but does not remove it. The queue is empty and throwsNoSuchElementExceptionException;

E getLast ();

Gets the last element of the queue, but does not remove it. The queue is empty and throwsNoSuchElementExceptionException;

E peekFirst ();

Obtain the first element of the queue. If the queue is empty, null is returned;

E peekLast ();

Get the last element of the queue. If the queue is empty, null is returned;

Boolean removeFirstOccurrence (Object o );

Remove the first satisfied(O = null? E = null: o. equals (e ))Element

Boolean removeLastOccurrence (Object o );

Remove the last(O = null? E = null: o. equals (e ))Element

Void push (E e );

Insert Object e into the head of the double-end queue;

E pop ();

Remove and return the first element of the double-ended queue

Iterator <E> descendingIterator ();

An iterator from the end of the dual-end queue to the header;

AbstractSequentialList class

An abstract class that implements Random Access to data based on the iterator. The meanings of the following methods are as follows. In short, they are random access to data (using an index );

Public E get (int index)

Public E set (int index, E element)

Public void add (int index, E element)

Public E remove (int index)

Public boolean addAll (int index, Collection <? Extends E> c)

Sort list class

Specific implementation of the shortlist,

The shortlist contains two key member attributes: The frontend node and the backend node:

Transient Node <E> first; // team head Node transient Node <E> last; // team End Node

Internal class of the worker list Node

The Code is as follows. Each node contains the reference of the previous node, the reference of the next node, and the specific object referenced by the node;

    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;        }    }

As for the meaning of each method provided by the consumer list, it is described in the previous interfaces such as queue, double-end queue, and set. Here we will briefly introduce the specific implementation of one or two methods. Let's take a look at the source code, it is actually a linked list operation:

Poll method, team-out operations

    public E poll() {        final Node<E> f = first;        return (f == null) ? null : unlinkFirst(f);    }
    /**     * Unlinks non-null first node f.     */    private E unlinkFirst(Node<E> f) {        // assert f == first && f != null;        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 = null;        else            next.prev = null;        size--;        modCount++;        return element;    }

Obtain and remove the elements in the header of the double-end queue. The code above mainly implements the unlinkFirst method. First, you can directly obtain the deleted vertices and temporarily store the referenced object element and the next referenced next, then, the deleted vertex object reference and the next node reference are set to null for gc collection, and the header node of the double-ended queue is changed to the next Reference next of the deleted vertex. If next is empty, set the last end node of the dual-end queue to null. Otherwise, set the first reference of the next node to null. The length of the queue is reduced, and the number of operations is added (fast failure mechanism ), returns the object referenced by the deleted vertex;

Public E get (int index) method, Random Access Method

    public E get(int index) {        checkElementIndex(index);        return node(index).item;    }
    /**     * Returns the (non-null) Node at the specified element 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;        }    }

Random list random access performance is poor. First, the index validity is determined, and then the node (int index) method is called. In the node method, some optimizations are made, first, determine whether the index of the node to be accessed is in the first half or the second half of the queue. If the first half is traversed from the head of the queue, otherwise, it is traversed from the end of the queue, as shown in the code above.

Notes

It is very important to use ArrayList. You must distinguish it from ArrayList. Select a proper List implementation based on the characteristics of the set and specific scenarios;

Here is a simple example. We use ArrayList and rule list to test the random access performance of the two sets. We can find that the efficiency of random access using rule list is much lower than that of ArrayList;

Package com. pickers. basis. col; import java. util. arrayList; import java. util. arrays; import java. util. iterator; import java. util. using list; import java. util. list; import java. util. listIterator; import java. util. stack; import java. util. vector; public class Test {public static void main (String [] args) {// initialize the struct list and arrayList data struct list <Integer> struct list = new struct list <Integer> (); for (int I = 0; I <10000; I ++) {vertex list. offerLast (I) ;}list <Integer> arrayList = new ArrayList <Integer> (); for (int I = 0; I <10000; I ++) {arrayList. add (I) ;}long s, e; s = System. currentTimeMillis (); for (int I = 0; I <10000; I ++) {memory list. get (I);} e = System. currentTimeMillis (); System. out. println ("Sort list:" + (e-s) + "ms"); s = System. currentTimeMillis (); for (int I = 0; I <10000; I ++) {arrayList. get (I);} e = System. currentTimeMillis (); System. out. println ("arrayList:" + (e-s) + "ms ");}}

Result printing:

linkedList:56msarrayList:1ms

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.