Java Queue implementation principle and simple implementation code _java

Source: Internet
Author: User
Tags int size ticket

Java Queue Implementation Principle

The word "queue" is a "platoon" spoken by the British. In Britain, "line up" means to stand in a row. In computer science, a queue is a data structure that resembles a stack, except that the first data item inserted in the queue is first removed, while in the stack the last item inserted is first removed. The role of the queue is like the people standing in front of the cinema: the first person to enter the subject will first arrive at the team head to buy tickets. The last person in line can finally get the ticket.

Queues and stacks are also used as tools for programmers. It can also be used to simulate real-world environments, such as simulating people waiting in queues in banks, planes waiting to take off, or packets waiting to be sent on the Internet.

In the computer operating system, there are various queues in the quiet work. The print job waits for printing in the print queue. When you tap on the keyboard, there is also a queue that stores the type of content. Similarly, if you use a word-processing program to hit a key, and the computer does something else for the time being, the percussion content is not lost and it waits in the queue until the word processor has a moment to read it. Queues ensure that the order of typing does not change as it is processed.

Basic operations for queues

The two basic operations of a queue are inserting (insert) a data item, which is to put one data item at the end of the team, and the other is to removing (remove) A data item, that is to remove the team header data items. This is similar to the movie lovers queuing up to buy a ticket to the end of the line, and then arrive at the team head and then leave the queue.

The Insert and remove data item methods in the stack are named very standard, called Push and pop. The method of queuing has not yet been standardized. "Insert" can be called put, add, or Enque, and "delete" can be called Delete, get, or deque. The end of the team in which the data item is inserted can also be called back, tail, or ends. The head of the team that removes the data item can also be called. Insert, remove, front, and rear are used below.

Inserts the value into the end of the team, and the team tail arrow increases one, pointing to the new data item.

When the data item is removed, the team head pointer increases one. Usually when the queue is implemented, the deleted data item is also saved in memory, except that it cannot be accessed because the team head pointer has moved to its next position.

Unlike in the stack, the data items in the queue do not always start at the 0 subscript of the array. When some data items are removed, the team head pointer points to a higher subscript position.

The view operation returns the value of the team header data item, but does not remove the data item from the team.

If you want to remove a data item from an empty queue or want to insert a data item in a full queue, the application prompts for an error message.

Looping queues

When you insert a new item in the queue, the rear arrow of the team head moves up and moves to the position where the array is marked. When you remove a data item, the end front pointer also moves up. This design may be the opposite of intuitive perception, because when people buy movie tickets in line, the team always moves forward, and when the front person buys the ticket and leaves the team, the others move forward. When you delete a data item in a queue in your computer, you can also move the other data items forward, but this is inefficient. Instead, we keep the position of all data items unchanged by the movement of the queue Squadron head and the tail pointer of the team.

The problem with this design is that the tail pointer will soon move to the end of the array. Although there is an empty data item cell at the beginning of the array, this is the position of the data item that was removed, but since the team tail pointer can no longer move backwards and therefore cannot insert a new data item, what should I do?

Wrap-around processing

To avoid the problem of inserting a new data item without a queue dissatisfaction, you can get the tail pointer of the team head around the beginning of the array. This is a circular queue (sometimes called a "buffer ring").

The process of pointer wrapping: inserting enough data items into the queue so that the tail pointer points to the end of the array. Then delete the data items from the front end of several arrays. Now insert a new data item. You will see the end of the tail pointer from the end to the beginning of the position. The new data item will be inserted in this position.

Insert more data items. The tail pointer moves upwards as expected. Note that after the tail pointer wraps, it is now under the team head pointer, which reverses the initial position. This can be called a broken sequence: a data item in a queue exists in an array of two different sequences.

After you delete enough data items, the team head pointer also wraps. At this point the queue's pointer returns to its initial run-time position, and the team head pointer is below the team's tail pointer. The data item also reverts to a single sequential sequence.

Java code for queues

The program creates a queue class that has inserts (), remove (), Peek (), IsEmpty (), and size () methods.

Package stacks and queues;

Class queue{private int maxSize;


    Private long[] Quearray;


    private int front;


    private int rear;



    private int nitems;


       Public Queue (int s) {maxsize=s;


       Quearray=new Long[maxsize];








       public void Insert (long j) {if (rear==maxsize-1) rear=-1;






       Public long Remove () {long temp=quearray[front++];


       if (front==maxsize) front=0;




    return temp;


    Public long Peekfront () {return quearray[front];


    public Boolean IsEmpty () {return (nitems==0);


    public Boolean iffull () {return (nitems==maxsize);


    public int size () {return nitems;






The program implementation of the queue class not only has front (team head) and rear (team tail) fields, as well as the number of current data items in the queue: Nitems.

The Insert () method runs in a condition where the queue is dissatisfied. This method is not shown in main (), but the insert () method should generally be invoked before the Isfull () method is called and false is returned. (A more common practice is to include a decision to check whether the queue is full in the Insert () method, and throw an exception if a data item is inserted into the full queue.) )

In general, the insert operation is the rear (team tail pointer) plus one, insert the new data at the point where the team tail pointer points. However, when the rear pointer points to the top of the array, that is, the maxSize-1 position, it must wrap around the bottom of the array before inserting the data item. The wrap operation sets the rear to 1, so when rear plus 1, it equals 0, which is the bottom of the array, and finally Nitem plus one.

The Remove () method runs in a condition where the queue is not empty, and you should call the IsEmpty () method before calling this method to ensure that the queue is not empty, or to include the error checking mechanism in the Remove () method.

The remove action always gets the value of the team header data item by the front pointer, and then adds front. However, if you do this so that the value of the front exceeds the top of the array, front must circle back to the position of the array subscript 0. For this test, the return value is temporarily stored first. Finally Nitem minus one.

The Peek () method is straightforward: it returns the value of the data item that the front pointer refers to. Some implementations of queues also allow you to view the values of the queue's trailing data items, such as Peekfront (), Peekrear (), or just front () and rear ().

Implementations of the IsEmpty (), Isfull (), and Size () methods depend on the Nitems field, which returns whether Nitems is equal to 0, equals maxsize, or returns its own value.

Including a data item in the Queue class Nitems the insert () and remove () methods add a little extra action because the insert () and remove () methods must increment and decrement the variable value separately. This may not be an extra overhead, but if you handle a large number of inserts and removal operations, this can affect performance.

Because the implementations of some queues do not use fields with data item counts, they calculate whether the queue is empty or full and the number of data items by front and rear. If you do this, the IsEmpty (), Iffull (), and size () routines can be quite complex, because as you've said before, the sequence of the data item is either folded into two paragraphs or a continuous paragraph.

Moreover, a strange problem arose. When the queue is full, the front and rear pointers take a certain position, but when the queue is empty, the same position relationship can also be rendered. So at the same time, the queue may seem full, or it may be empty. The solution to this problem is that the maximum size of the array capacity is greater than the number of data items in the queue.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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: 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.