본문 바로가기
IT/Java

자바 Queue 알아보기

by flatsun 2019. 2. 12.
반응형

이번에는 Stack과 자주 비교되는 Queue에 대해 알아보고 넘어간다


큐도 딱 보면 별로 어렵지 않은데

스택처럼 단순하기 때문이다


스택은 프링글스 생각하면 되지 않았나

나중에 들어온걸 제일 처음에 먹는 그것!!

전문용어로


LIFO

Last In First Out 이라고 했었는데


Queue 같은 경우에는

제일 처음에 들어온게 제일 먼저 나간다


그걸 어렵게 말하면?


FIFO

First In First Out!!!!


처음 들어온게 처음에 나간다!!!


간단히 알아봤으니 정의하고 출력이나 해 보자




Queue<자료형> Queue명 = new LinkedList<자료형>( 크기(입력 안할시 늘어났다 줄어들었다..) );


로 정의가 가능하다


큐 안에 넣을 때에는

Queue명.offer(값);


큐에서 값을 빼낼 때에는

Queue명.poll();


으로 빼내는데


뭔가 스택 큐 이러면 존나 난해해 보이지만

우리는 그런 난해한 영역까지는 사용하지 않고


단순하게 넣었다 빼는 두개만 사용하므로

그거 두개만 놓고 보면 매우 단순한 것을 알 수 있다


offer로 넣고 poll로 뺀다!


근데 queue 같은 경우에는

먼저 들어간게 먼저 나온다


이걸 어려운 용어로

FIFO

First In First Out이라고 한다!!!


이제 출력을 한번 해볼까?



짜잔~


아까 1,2,3,4,5를 순서대로 넣었는데

넣은 순서대로 출력이 되었다


이제 Queue의 메소드에 대해 알아보자


1
2
3
4
        q.remove();
        System.out.println(q.peek());
        System.out.println(q.element());
        q.add(6);
cs


Stack과 동일하게 거의 없는 수준인데


Queue명.remove()

- 다음에 출력될 값을 지운다


Queue명.peek()

- 다음에 출력될 값을 확인


Queue명.element()

- 다음에 출력될 값을 확인, peek과 다른점은 Queue에서 다 뽑아내거나 Queue가 비어있으면 에러가 출력된다


Queue명.add(값)

- 값을 Queue의 끝에 추가한다 offer와 다른점은 큐가 꽉 차서 추가할 수 없는 경우에는 에러가 출력된다


1
2
3
4
5
6
7
8
9
10
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
        queue.add("TestQuue1");     
        queue.add("TestQuue2"); 
        queue.add("TestQuue3");
 
Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(Unknown Source)
    at java.util.concurrent.ArrayBlockingQueue.add(Unknown Source)
    at first.QueueTest.main(QueueTest.java:32)
 
cs


마지막으로

Queue를 여러 형태로 정의할 수 있는데



인간적으로 너무 종류가 많아서 설명하기 힘들고

나도 잘 모른다!


하지만 PriorityQueue만 보고 넘어가자면

우선순위 큐인데


넣는 순서대로 나오는게 아니라 값 순서에 따라 출력이 된다!!


정의는 하단 코드를 참고하자


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    public static void main(String[] args) {
        
        PriorityQueue<Integer> q = new PriorityQueue<Integer>();
        
        q.offer(200);
        q.offer(50);
        q.offer(93);
        q.offer(7);
        q.offer(80);
        
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
 
    }
 
 
7
50
80
93
200
cs


작은 값이 먼저 나오는게 아니라

큰 값이 먼저 나오게 하고 싶을 수도 있는데


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    public static void main(String[] args) {
        
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(Collections.reverseOrder());
        
        q.offer(200);
        q.offer(50);
        q.offer(93);
        q.offer(7);
        q.offer(80);
        
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
 
    }
 
200
93
80
50
7
cs


크기 부분에 Collections.reverseOrder()를 추가해주면 역순도 십 가능이다!!

반응형

댓글