31
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java スタック、キュー

Posted at

キュー

Queue

機能 メソッド名 備考
追加 add / offer 容量制限がある場合は offer 推奨
取出し remove / poll 空のとき 例外を起こす / null を返す
参照 element / peek 空のとき 例外を起こす / null を返す
SampleQueue.java
import java.util.Queue;
import java.util.ArrayDeque;

public class SampleQueue {
    public static void main(String[] args){
        Queue<Integer> queue = new ArrayDeque<Integer>();
        for (int i=0;i<100;i++) queue.add(i);
        while(true){
            Integer a = queue.poll();
            if (a == null) break;
            System.out.print(a + " ");
        }
        System.out.println("");
    }   
}

スタック

Deque

スタックは java.util.Stack よりも java.util.Deque インタフェースを使ったほうが良いらしい
キューの場合と比べて、追加メソッドが変わっただけで 取出し、参照は変わらない

機能 メソッド名 備考
追加 push / offerFirst 容量制限がある場合は offerFirst 推奨
取出し remove / poll 空のとき 例外を起こす / null を返す
参照 element / peek 空のとき 例外を起こす / null を返す
SampleDeque.java
import java.util.Deque;
import java.util.ArrayDeque;

public class SampleDeque {
    public static void main(String[] args){
        Deque<Integer> stack = new ArrayDeque<Integer>();
        for (int i=0;i<100;i++) stack.push(i);
        while(true){
            Integer a = stack.poll();
            if (a == null) break;
            System.out.print(a + " ");
        }
        System.out.println("");
    }   
}
31
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?