java Queue
In Java, a Queue is a data structure that follows the First-In-First-Out (FIFO) principle. It is an interface that is a part of the Java Collections Framework.
Some common implementations of the Queue interface in Java include:
- LinkedList: A doubly-linked list that can be used as a Queue.
- ArrayDeque: A resizable array that can be used as a Queue.
- PriorityQueue: A Queue that orders its elements based on their natural ordering or a specified Comparator.
Here is an example of how to use a LinkedList as a Queue in Java:
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// Adding elements to the Queue
queue.add("Element 1");
queue.add("Element 2");
queue.add("Element 3");
// Accessing and removing elements from the Queue
String element = queue.poll();
System.out.println("Removed element: " + element);
// Accessing the head of the Queue without removing it
String head = queue.peek();
System.out.println("Head of the Queue: " + head);
// Checking if the Queue is empty
boolean isEmpty = queue.isEmpty();
System.out.println("Is the Queue empty? " + isEmpty);
}
}
Output:
Removed element: Element 1
Head of the Queue: Element 2
Is the Queue empty? false
In the example above, we create a Queue using a LinkedList implementation. We add elements to the Queue using the add() method. We then remove an element from the Queue using the poll() method, which returns and removes the head of the Queue. We access the head of the Queue without removing it using the peek() method. Finally, we check if the Queue is empty using the isEmpty() method
原文地址: http://www.cveoy.top/t/topic/iKnH 著作权归作者所有。请勿转载和采集!