📜  Java中的队列接口

📅  最后修改于: 2022-05-13 01:54:46.027000             🧑  作者: Mango

Java中的队列接口

Java.util 包中存在并扩展了 Collection 接口的 Queue 接口用于保存即将按 FIFO(先进先出)顺序处理的元素。它是一个有序的对象列表,其用途仅限于在列表末尾插入元素并从列表开头删除元素,(即)它遵循 FIFO 或先进先出原则。

Queue-Deque-PriorityQueue-In-Java

作为一个接口,队列需要一个具体的声明类,最常见的类是Java中的 PriorityQueue 和 LinkedList 。请注意,这些实现都不是线程安全的。如果需要线程安全实现,PriorityBlockingQueue 是一种替代实现。

声明: Queue接口声明为:

创建队列对象
由于Queue是一个接口,因此无法创建队列类型的对象。我们总是需要一个扩展这个列表的类来创建一个对象。而且,在Java 1.5 中引入泛型之后,可以限制可以存储在队列中的对象类型。这个类型安全的队列可以定义为:

队列示例:

Java
// Java program to demonstrate a Queue
 
import java.util.LinkedList;
import java.util.Queue;
 
public class QueueExample {
 
    public static void main(String[] args)
    {
        Queue q
            = new LinkedList<>();
 
        // Adds elements {0, 1, 2, 3, 4} to
        // the queue
        for (int i = 0; i < 5; i++)
            q.add(i);
 
        // Display contents of the queue.
        System.out.println("Elements of queue "
                           + q);
 
        // To remove the head of queue.
        int removedele = q.remove();
        System.out.println("removed element-"
                           + removedele);
 
        System.out.println(q);
 
        // To view the head of queue
        int head = q.peek();
        System.out.println("head of queue-"
                           + head);
 
        // Rest all methods of collection
        // interface like size and contains
        // can be used with this
        // implementation.
        int size = q.size();
        System.out.println("Size of queue-"
                           + size);
    }
}


Java
// Java program to add elements
// to a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        System.out.println(pq);
    }
}


Java
// Java program to remove elements
// from a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        System.out.println("Initial Queue " + pq);
 
        pq.remove("Geeks");
 
        System.out.println("After Remove " + pq);
 
        System.out.println("Poll Method " + pq.poll());
 
        System.out.println("Final Queue " + pq);
    }
}


Java
// Java program to iterate elements
// to a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        Iterator iterator = pq.iterator();
 
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}


Java
// Java program to demonstrate the
// creation of queue object using the
// PriorityQueue class
 
import java.util.*;
 
class GfG {
 
    public static void main(String args[])
    {
        // Creating empty priority queue
        Queue pQueue
            = new PriorityQueue();
 
        // Adding items to the pQueue
        // using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
 
        // Printing the top element of
        // the PriorityQueue
        System.out.println(pQueue.peek());
 
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
 
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}


Java
// Java program to demonstrate the
// creation of queue object using the
// LinkedList class
 
import java.util.*;
 
class GfG {
 
    public static void main(String args[])
    {
        // Creating empty LinkedList
        Queue ll
            = new LinkedList();
 
        // Adding items to the ll
        // using add()
        ll.add(10);
        ll.add(20);
        ll.add(15);
 
        // Printing the top element of
        // the LinkedList
        System.out.println(ll.peek());
 
        // Printing the top element and removing it
        // from the LinkedList container
        System.out.println(ll.poll());
 
        // Printing the top element again
        System.out.println(ll.peek());
    }
}


Java
// Java program to demonstrate the
// creation of queue object using the
// PriorityBlockingQueue class
 
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
 
class GfG {
    public static void main(String args[])
    {
        // Creating empty priority
        // blocking queue
        Queue pbq
            = new PriorityBlockingQueue();
 
        // Adding items to the pbq
        // using add()
        pbq.add(10);
        pbq.add(20);
        pbq.add(15);
 
        // Printing the top element of
        // the PriorityBlockingQueue
        System.out.println(pbq.peek());
 
        // Printing the top element and
        // removing it from the
        // PriorityBlockingQueue
        System.out.println(pbq.poll());
 
        // Printing the top element again
        System.out.println(pbq.peek());
    }
}


输出:
Elements of queue [0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4

队列接口操作

让我们看看如何使用 Priority Queue 类对队列执行一些常用的操作。
1. 添加元素:为了在队列中添加元素,我们可以使用 add() 方法。插入顺序不会保留在 PriorityQueue 中。元素根据默认升序的优先级顺序存储。

Java

// Java program to add elements
// to a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        System.out.println(pq);
    }
}
输出:
[For, Geeks, Geeks]

2. 移除元素:为了从队列中移除一个元素,我们可以使用 remove() 方法。如果有多个这样的对象,则删除第一次出现的对象。除此之外,poll() 方法还用于移除头部并返回它。

Java

// Java program to remove elements
// from a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        System.out.println("Initial Queue " + pq);
 
        pq.remove("Geeks");
 
        System.out.println("After Remove " + pq);
 
        System.out.println("Poll Method " + pq.poll());
 
        System.out.println("Final Queue " + pq);
    }
}
输出:
Initial Queue [For, Geeks, Geeks]
After Remove [For, Geeks]
Poll Method For
Final Queue [Geeks]

3. 迭代队列:有多种方法可以迭代队列。最著名的方法是将队列转换为数组并使用 for 循环进行遍历。但是,队列也有一个内置的迭代器,可用于遍历队列。

Java

// Java program to iterate elements
// to a Queue
 
import java.util.*;
 
public class GFG {
 
    public static void main(String args[])
    {
        Queue pq = new PriorityQueue<>();
 
        pq.add("Geeks");
        pq.add("For");
        pq.add("Geeks");
 
        Iterator iterator = pq.iterator();
 
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}
输出:
For Geeks Geeks

队列的特征以下是队列的特征:

  • Queue 用于在队列末尾插入元素并从队列开头移除元素。它遵循先进先出的概念。
  • Java Queue 支持 Collection 接口的所有方法,包括插入、删除等。
  • LinkedList、ArrayBlockingQueue 和 PriorityQueue 是最常用的实现。
  • 如果对 BlockingQueues 执行任何空操作,则抛出 NullPointerException。
  • Java.util 包中可用的队列是无界队列。
  • Java.util.concurrent 包中可用的队列是有界队列。
  • 除 Deques 之外的所有队列都支持在队列的尾部和头部分别插入和删除。 Deques 支持在两端插入和删除元素。

实现队列接口的类:

1. PriorityQueue:在集合框架中实现的PriorityQueue类为我们提供了一种基于优先级处理对象的方法。众所周知,队列遵循先进先出的算法,但有时需要根据优先级对队列中的元素进行处理,这时PriorityQueue就派上用场了。让我们看看如何使用这个类创建一个队列对象。

Java

// Java program to demonstrate the
// creation of queue object using the
// PriorityQueue class
 
import java.util.*;
 
class GfG {
 
    public static void main(String args[])
    {
        // Creating empty priority queue
        Queue pQueue
            = new PriorityQueue();
 
        // Adding items to the pQueue
        // using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
 
        // Printing the top element of
        // the PriorityQueue
        System.out.println(pQueue.peek());
 
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
 
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}
输出:
10
10
15

2. LinkedList: LinkedList是一个在集合框架中实现的类,它固有地实现了链表数据结构。它是一种线性数据结构,其中元素不存储在连续的位置,每个元素都是具有数据部分和地址部分的单独对象。元素使用指针和地址链接。每个元素称为一个节点。由于插入和删除的动态性和易用性,它们优于数组或队列。让我们看看如何使用这个类创建一个队列对象。

Java

// Java program to demonstrate the
// creation of queue object using the
// LinkedList class
 
import java.util.*;
 
class GfG {
 
    public static void main(String args[])
    {
        // Creating empty LinkedList
        Queue ll
            = new LinkedList();
 
        // Adding items to the ll
        // using add()
        ll.add(10);
        ll.add(20);
        ll.add(15);
 
        // Printing the top element of
        // the LinkedList
        System.out.println(ll.peek());
 
        // Printing the top element and removing it
        // from the LinkedList container
        System.out.println(ll.poll());
 
        // Printing the top element again
        System.out.println(ll.peek());
    }
}
输出:
10
10
20

3. PriorityBlockingQueue:需要注意的是,PriorityQueue 和 LinkedList 这两个实现都不是线程安全的。如果需要线程安全实现,PriorityBlockingQueue 是一种替代实现。 PriorityBlockingQueue 是一个无界阻塞队列,它使用与类 PriorityQueue 相同的排序规则并提供阻塞检索操作。
由于它是无界的,添加元素有时可能会由于资源耗尽而失败,从而导致 OutOfMemoryError。让我们看看如何使用这个类创建一个队列对象。

Java

// Java program to demonstrate the
// creation of queue object using the
// PriorityBlockingQueue class
 
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
 
class GfG {
    public static void main(String args[])
    {
        // Creating empty priority
        // blocking queue
        Queue pbq
            = new PriorityBlockingQueue();
 
        // Adding items to the pbq
        // using add()
        pbq.add(10);
        pbq.add(20);
        pbq.add(15);
 
        // Printing the top element of
        // the PriorityBlockingQueue
        System.out.println(pbq.peek());
 
        // Printing the top element and
        // removing it from the
        // PriorityBlockingQueue
        System.out.println(pbq.poll());
 
        // Printing the top element again
        System.out.println(pbq.peek());
    }
}
输出:
10
10
15

队列接口的方法

queue 接口继承了 collections 接口中的所有方法,同时实现了以下方法:

Method

Description

add(int index, element)This method is used to add an element at a particular index in the list. When a single parameter is passed, it simply adds the element at the end of the list.
addAll(int index, Collection collection)This method is used to add all the elements in the given collection to the list. When a single parameter is passed, it adds all the elements of the given collection at the end of the list.
size()This method is used to return the size of the list.
clear()This method is used to remove all the elements in the list. However, the reference of the list created is still stored.
remove(int index)This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
remove(element)This method is used to remove and return the first occurrence of the given element in the list.
get(int index)This method returns elements at the specified index.
set(int index, element)This method replaces elements at a given index with the new element. This function returns the element which was just replaced by a new element.
indexOf(element)This method returns the first occurrence of the given element or -1 if the element is not present in the list.
lastIndexOf(element)This method returns the last occurrence of the given element or -1 if the element is not present in the list.
equals(element)This method is used to compare the equality of the given element with the elements of the list.
hashCode()This method is used to return the hashcode value of the given list.
isEmpty()This method is used to check if the list is empty or not. It returns true if the list is empty, else false.
contains(element)This method is used to check if the list contains the given element or not. It returns true if the list contains the element.
containsAll(Collection collection)This method is used to check if the list contains all the collection of elements.
sort(Comparator comp)This method is used to sort the elements of the list on the basis of the given comparator.