>  기사  >  Java  >  자바의 큐

자바의 큐

WBOY
WBOY원래의
2024-08-30 16:03:40987검색

큐 데이터 구조는 FIFO(선입선출) 원칙을 사용합니다. 처리할 개체를 도착 순서대로 보관하는 데 사용됩니다. 이것은 줄을 서 있는 사람들의 줄과 매우 유사합니다. Java는 Collection 인터페이스 형태로 데이터 구조에 대한 대규모 지원을 제공하므로 큐는 Collection 인터페이스에서 사용할 수 있는 인터페이스입니다. Collection 인터페이스를 확장합니다. Java.util 패키지에서 사용할 수 있으며 몇 가지 추가 추출, 삽입 및 검사 작업과 함께 Collection 인터페이스에서 사용할 수 있는 모든 작업을 지원합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문:

Interface Queue<E>

큐는 클래스가 아닌 인터페이스이므로 직접 인스턴스화할 수 없습니다. 선언은 대기열이 컬렉션과 유사한 일반적인 값을 허용하며 모든 객체를 대기열에 전달할 수 있음을 보여줍니다. Java에는 대기열을 사용하는 동안 사용할 수 있는 대기열 인터페이스의 여러 구현이 있습니다. LinkedList와 PriorityQueue가 있습니다.

큐는 아래와 같이 선언할 수 있습니다.

Queue< Object > q = new LinkedList<>();
Queue< Object > q = new PriorityQueue<>();

Java에서 대기열은 어떻게 작동하나요?

  • 앞서 설명한 것처럼 대기열 인터페이스는 컬렉션 인터페이스를 확장합니다. 따라서 사용 가능한 모든 기본 작업 방법을 지원합니다.
  • LinkedList 및 PriorityQueue와 같은 구현은 대기열 인터페이스에 선언된 대기열별 메서드를 구현합니다.
  • LinkedList는 LinkedList의 표준, 즉 삽입 순서대로 요소를 보유합니다. PriorityQueue는 삽입된 요소의 자연스러운 순서를 유지합니다.
  • 이 두 구현은 스레드로부터 안전하지 않으며 이를 위해 Java는 스레드로부터 안전한 PriorityBlockingQueue라는 또 다른 구현을 제공합니다.

Java의 대기열 구성원 유형

  • 큐는 인터페이스이므로 추상 메소드만 포함하고 데이터 멤버는 포함하지 않습니다.
  • 큐는 하위 클래스에 구현된 작업을 정의하는 방법만 제공합니다.

Java의 대기열 함수

  • 큐는 FIFO 구조를 지원하므로 한쪽 끝에서 요소를 삽입하고 다른(프론트) 끝에서 요소를 제거할 수 있습니다.
  • 큐에서 지원하는 두 가지 기본 작업은 다음과 같습니다.
  • 대기열에서 사용할 수 있는 모든 메서드는 두 가지 범주로 나눌 수 있습니다. 첫 번째 유형의 메소드는 요소를 찾을 수 없는 등 작업 실패 시 예외를 발생시키고, 두 번째 유형의 메소드는 작업 실패 시 예외 대신 null 또는 false와 같은 특정 값을 반환합니다. .
  • 대기열 개념의 헤드는 항상 대기열의 첫 번째 요소를 나타냅니다. 제거 시 이 헤드 요소가 먼저 제거됩니다.

다음은 대기열에서 사용할 수 있는 모든 방법입니다.

  Returns special value Throws exception
Insert offer(e) add(e)
Remove poll() remove()
Examine peek() element()
  특수 값을 반환합니다 예외 발생 삽입 제안(e) 추가(e) 삭제 설문조사() 제거() 조사 엿보기() 요소()

So as explained, two types of methods throw an exception and return a special value. There are three types of operation in this kind of operation: insertion, the second is removal, and the third is retrieval or examination. In the case of the remove operation, an object will be removed from the queue. Still, in the case of examination, the object will be returned without actually removing from the queue.

Examples of Queue in Java

Given below are the different examples of Queue in Java:

Example #1 – Add operation with LinkedList implementation

Code:

import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer> ();
q.add(5);
q.add(2);
q.add(1);
q.add(4);
q.add(3);
System.out.println(q);
}
}

Output:

자바의 큐

Note here that the order of insertion is the same with output from left to write.

Example #2 – Let’s remove the added elements one by one

Code:

import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer> ();
q.add(5);
q.add(2);
q.add(1);
q.add(4);
q.add(3);
System.out.println(q);
while (!q.isEmpty()) {
System.out.print(q.remove() + " ");
}
System.out.println("");
System.out.println(q);
}
}

Output:

자바의 큐

Here, we have used the function isEmpty() to check when the queue becomes empty after removing elements. The removal order is the same as per the insertion. After removing all the elements, we printed the queue and obtained an empty bracket at the end.

Example #3 – Insertion and Removal Operation on PriorityQueue

Code:

import java.util.PriorityQueue;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> q = new PriorityQueue<Integer> ();
q.add(5);
q.add(2);
q.add(1);
q.add(4);
q.add(3);
System.out.println(q);
while (!q.isEmpty()) {
System.out.print(q.remove() + " ");
}
System.out.println("");
System.out.println(q);
}
}

Output:

자바의 큐

Here, we have used PriorityQueue, which will hold and return the elements depending upon the elements’ natural ordering or upon the comparator, if any passed. Note the insertion order and removal orders are not the same. The removal is based totally on the value of elements.

Example #4 – Examine operation on LinkedList

Code:

import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer> ();
q.add(5);
q.add(2);
q.add(1);
q.add(4);
q.add(3);
System.out.println(q);
System.out.println( q.peek() );
System.out.println(q);
}
}

Output:

자바의 큐

Note here that we have used the peek() function, which will return the head of the queue without actually removing it. We printed the queue after performing the peek operation, and you can observe that the head element, which is 5, remains unchanged in the queue.

Example #5 – Examine operation on PriorityQueue

Code:

import java.util.PriorityQueue;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> q = new PriorityQueue<Integer> ();
q.add(5);
q.add(2);
q.add(1);
q.add(4);
q.add(3);
System.out.println(q);
System.out.println( q.peek() );
System.out.println(q);
}
}

Output:

자바의 큐

This is similar to the previous example’s LinkedList operation, but note the head element is 1 because it’s a PriorityQueue.

Conclusion

Java utilizes the Queue interface as a means to maintain elements in insertion order. It supports operations like insertion, retrieval, and removal. There are alternative methods available for all the methods. We have seen examples of the most commonly used methods in queue operation.

위 내용은 자바의 큐의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 협회다음 기사:자바 협회