[Java] 컬렉션(Queue) : LinkedList

정재현·2024년 1월 3일

Java

목록 보기
20/43
post-thumbnail

Queue

  • 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합
  • FIFO(First In First Out) : 먼저들어간 순서대로 나온다
  • 생성자가 없는 인터페이스
    • Queue의 자식인 LinkedList를 이용해서 생성

사용할 때

  • 먼저 넣은 값을 먼저 사용하고자 할 때

기능

  • 선언 : Queue<Integer> intQueue 형태로 선언
  • 생성 : new LinkedList<Integer>(); 형태로 생성
    • 생성자가 없는 인터페이스이기 때문에 Queue를 이용해 생성할 수 없음

주요 기능

  • 추가 : add(추가할 값) 형태로 값을 맨 위에 추가
  • 조회 : peek() 형태로 맨 아래값을 조회
  • 꺼내기 : poll() 형태로 맨 아래값을 꺼냄 (꺼내고나면 삭제됨)

기타 기능

  • 비었는지 확인 : isEmpty() 형태로 배열이 비어있으면 true, 아니면 false 반환

생성 방법

  • Queue는 생성자가 없는 인터페이스라서 바로 생성할 수는 없다.
  • 생성자가 존재하는 클래스인 LinkedList를 사용하여 Queue를 생성해서 받을 수 있음
    • LinkedList 를 생성하면 Queue 기능을 할 수 있다.
    • Queue가 부모클래스(인터페이스), LinkedList 가 자식클래스
	Queue<Integer> intQueue = new LinkedList<Integer>();

예시

// Queue 
// (사용하기 위해선 java.util.LinkedList; 와 import java.util.Queue; 를 추가해야함)
import java.util.LinkedList;
import java.util.Queue;

public class Main {

	public static void main(String[] args) {
		Queue<Integer> intQueue = new LinkedList<>(); // 선언 및 생성

		intQueue.add(1);
		intQueue.add(2);
		intQueue.add(3);

		while (!intQueue.isEmpty()) { // 다 지워질때까지 출력
			System.out.println(intQueue.poll()); // 1,2,3 출력
		}

		// 다시 추가
		intQueue.add(1);
		intQueue.add(2);
		intQueue.add(3);

		// peek()
		System.out.println(intQueue.peek()); // 1 출력 (맨먼저 들어간값이 1 이라서)
		System.out.println(intQueue.size()); // 3 출력 (peek() 할때 삭제 안됬음)

		// poll()
		System.out.println(intQueue.poll()); // 1 출력
		System.out.println(intQueue.size()); // 2 출력 (poll() 할때 삭제 됬음)

		System.out.println(intQueue.poll()); // 2 출력
		System.out.println(intQueue.size()); // 1 출력 (poll() 할때 삭제 됬음)

		while (!intQueue.isEmpty()) { // 다 지워질때까지 출력
			System.out.println(intQueue.poll()); // 3 출력 (마지막 남은거 하나)
		}
	}
}

profile
공부 기록 보관소

0개의 댓글