Search code examples
javadequearraydeque

Assigning a size to a Deque in Java


I'm having trouble assigning a limit to the size of my double ended queue (Deque). It seems that my queue never gets full and just resizes whenever I add or offer a value unto it. My simple code just accepts a string value, splits it by space " ", loops everything and adds it to the queue.

evaluate("A B C D E F");

public static int evaluate(final String input){
    final Deque<String> stack = new ArrayDeque<>(3);
    final String[] tokens = input.split(" ");


    for (String token:tokens){
        System.out.println(stack.offer(token));
    }

    System.out.println(stack.size());
 }

returns:

 true
 true
 true
 true
 true
 true
 6

I was expecting that the queue will be full since I have not removed or read any value from it. Is there something that I'm missing here? Or am I just using the queue wrong? Thanks!


Solution

  • I advise you to implement your own class with desired behaviour. Otherwise already exists classes that remove the excessive elements. See this answer https://stackoverflow.com/a/21699069/228358