Understanding Java collection from the to the very point (iv)

Source: Internet
Author: User
Understanding Java Collection (Iv.)--Collection-queueTags: Java data Structure Collection Class Foundation 2017-05-25 12:33 54 people read Comments (0) Favorites Report Category: Java Learning (4)

Copyright NOTICE: This article is the original article of the blogger, without the permission of the blogger may not be reproduced.

Directory (?) [+]

Today we are going to introduce several important implementation classes in the next set queue. There is less content about the collection queue. The implementation classes in the queue are introduced mainly for the use of the data structure of queues.

Queues are used to simulate the data structures of queues, which usually refer to "First-in First Out" (FIFO) containers. The new element inserts (offer) to the end of the queue, and the Access Element (poll) operation returns the elements of the queue's head. Typically, queues do not allow random access to elements in the queue.

This structure is like a line in our lives.

Here we will introduce an important implementation class Priorityqueue in the queue. Priorityqueue

Priorityqueue the order in which the queue elements are saved is not in the order in which they were queued, but by the size of the queue elements. So when you call the Peek () or pool () method to remove the elements of the header in the queue, you do not remove the element that first enters the queue, but instead take the smallest element out of the queue. How to sort priorityqueue

Elements in Priorityqueue can be naturally sorted by default (that is, numbers are small by default in the queue header, strings are in dictionary order), or by the provided comparator (comparer) that is specified when the queue is instantiated. About natural sorting and comparator (comparators) can refer to my explanation when introducing set set.
Note: The header of the queue is the smallest element that is sorted by the specified method. If more than one element is a minimum, the header is one of the elements--the selection method is arbitrary.

Note: When comparator is not specified in the Priorityqueue, the element that joins the Priorityqueue must implement the comparable interface (that is, the element is comparable), or it can cause classcastexception. &NBSP
Here's a concrete example to show how to sort in Priorityqueue:

priorityqueue<integer> qi = new priorityqueue<integer> ();
        Qi.add (5);
        Qi.add (2);
        Qi.add (1);
        Qi.add (10);
        Qi.add (3);
        while (!qi.isempty ()) {System.out.print (Qi.poll () + ",");
        } System.out.println (); In descending order, the smaller the queue at the end of the queue comparator<integer> cmp = new comparator<integer> () {public int compar
          E (integer e1, integer e2) {return e2-e1;
        }
        };
        priorityqueue<integer> q2 = new priorityqueue<integer> (5,CMP);
        Q2.add (2);
        Q2.add (8);
        Q2.add (9);
        Q2.add (1);
            while (!q2.isempty ()) {System.out.print (Q2.poll () + ","); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18-------------19 20 21 22 23 24 1 2 3-4 5 6 7, 8 24

Output results:

1,2,3,5,10,
9,8,2,1,

From this we can see that by default the Priorityqueue is sorted by nature. When specifying comparator, the Priorityqueue takes the specified sort. the method of Priorityqueue

Priorityqueue implements the queue interface, and the Priorityqueue method is listed below.
the essence of Priorityqueue

The Priorityqueue essence is also a dynamic array, which is consistent with ArrayList in this respect.
When Priorityqueue calls the default construction method, a priorityqueue is created using the default initial capacity (DEFAULT_INITIAL_CAPACITY=11). and sort its elements according to their natural order (comparable implemented using the collection elements that are added to them).

Public Priorityqueue () {This
        (default_initial_capacity, null);
    }
1 2 3 1 2 3

When a constructed method of a specified capacity is used, a priorityqueue is created with the specified initial capacity, and its elements are sorted according to their natural order (comparable that is implemented using the collection elements to which it is added).

Public priorityqueue (int initialcapacity) {This
        (initialcapacity, null);
    }
1 2 3 1 2 3

Creates a priorityqueue using the specified initial capacity and sorts its elements according to the specified comparer comparator.

Public priorityqueue (int initialcapacity,
                         comparator< Super e> Comparator) {
        //note:this restriction of At least one isn't actually needed,
        //But continues for 1.5 compatibility
        if (Initialcapacity < 1)
            throw New IllegalArgumentException ();
        This.queue = new Object[initialcapacity];
        This.comparator = comparator;
    }
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8-9

As can be seen from the third construction method, a dynamic array is maintained internally. When adding elements to the collection, the array is checked to see if there is more than enough to add the new element to the collection, and the Grow () method is called to add the capacity, and then call Siftup to insert the newly added elements into the corresponding position.

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;
    }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13-14

In addition, you should also note:
①priorityqueue is not thread-safe. If any thread in multiple threads has modified the list from the structure, the threads should not access the Priorityqueue instance at the same time, then use the thread-safe Priorityblockingqueue class.

② does not allow null elements to be inserted.

③priorityqueue the time complexity of implementing the Insert method (offer, poll, remove (), and Add method) is O (log (n)), and the time complexity of implementing the Remove (object) and contains (object) method is O (n) ; The time complexity of implementing the retrieval method (peek, element, and size) is O (1). So in the traversal, if you don't need to delete the elements, you iterate through each element in Peek mode.

The iterator provided in the ④ method iterator () does not guarantee an orderly traversal of elements in the superior priorityqueue. Dueue interface and Arraydeque implementation class Dueue Interface

The Deque interface is a sub-interface of the queue interface, which represents a two-terminal queue. LinkedList also implements the Deque interface, so it can also be used as a two-terminal queue. You can also see the front facing LinkedList introduction to understand the Deque interface.
Therefore, the Deque interface adds some methods for two-terminal queue operations.

void AddFirst (e E): Inserts the specified element at the beginning of this list.
void AddLast (E E): Adds the specified element to the end of this list.
E GetFirst (e E): Returns the first element of this list.
E GetLast (e E): Returns the last element of this list.
Boolean Offerfirst (E E): Inserts the specified element at the beginning of this list.
Boolean offerlast (E E): Inserts the specified element at the end of this list.
E Peekfirst (e E): Gets but does not remove the first element of this list, or null if the list is empty.
e Peeklast (E): Gets but does not remove the last element of this list, or returns null if the list is empty.
E Pollfirst (e E): Gets and removes the first element of this list, or null if the list is empty.
E Polllast (e E): Gets and removes the last element of this list, or null if the list is empty.
E Removefirst (e E): Removes and returns the first element of this list.
Boolean removefirstoccurrence (Objcet o): Removes the first occurrence of the specified element from the list (when traversing the list from head to tail).
E Removelast (e E): Removes and returns the last element of this list.
Boolean removelastoccurrence (Objcet o): Removes the last occurrence of the specified element from the list (when traversing the list from head to tail).

As can be seen from the above method, deque not only can be used as a two-terminal queue, but can be used as a stack, because the class also contains pop (out of stack), push (stack) two methods. the relationship between Deque and queue and stack

When Deque is used as a queue queuing (FIFO), the add element is added to the team tail and deletion is the head element. Methods that inherit from the Queue interface correspond to the Deque method as shown in the figure:

Deque can also be used as stack stacks (LIFO). At this time the stack, the stack elements are in the head of the two-terminal queue. The Deque and stack corresponding methods are shown in the figure:

* * Note: **stack is too old, and realize very bad, so now basically no longer, you can directly use Deque to replace the stack into broker's storehouses operation. Arraydeque

As the name suggests, is to use array implementation of the deque; Since the bottom is an array, you can definitely specify its capacity, or unspecified, the default length is 16, and then dynamically expand according to the number of elements added. Arraydeque because it is a two-sided queue, the order is generated according to the corresponding position in the array in which the element is inserted (described below).
Due to the limitations of its own data structure, Arraydeque does not have the TrimToSize method like ArrayList to slim himself. Arraydeque use method is the above deque use method, basically did not extend to deque what method. the essence of Arraydeque

Loop array
Arraydeque in order to satisfy the requirement that elements can be inserted or deleted at both ends of the array, the dynamic array within it must also be circular, that is, the loop array (circular array), in other words, any point of the array may be considered as the starting point or end point.
The Arraydeque maintains two variables, representing the head and tail of the arraydeque.

transient int head;
 transient int tail;
1 2 1 2

When you insert an element into the head, it is marked down and inserted into the element. The index represented by tail is the index value of the current end element plus one. If you insert an element into the tail, insert it directly into the position indicated by the tail, and then tail one more.
Specifically, the following picture for example explained.

In the illustration above: The left figure indicates that 4 elements were inserted from the head, and 2 were inserted in the tail. At the beginning, head=0,tail=0. When the element 5,head-1 is inserted from the head, as the array is a looping array, the last position to move to the array is inserted at 5. When inserting elements from the head 34,head

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.