5

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!

Juni
  • 79
  • 2
  • 7
  • You are missing reading the Javadoc - `Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage`. – Eran Jun 07 '17 at 10:13
  • I see, any suggestions if there are any types of queue that implement that kind of characteristic? – Juni Jun 07 '17 at 10:18

2 Answers2

0

When you do

Deque<String> stack = new ArrayDeque<>(3);

3 is not the size but the initial capacity as the doc explains here

the ArrayDeque can grow as much as you need, and you are not limiting the size with that parameter in the constructor.


you can handle a work around dont exposing the array but instead checking everytime you want to add/offer an object in the deque

if (stack.size()<3) {
    stack.offer(token);
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • oh I see, well if that's the case, do you know of any way to limit the size of the ArrayDeque? – Juni Jun 07 '17 at 10:16
0

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

Valerio Emanuele
  • 909
  • 13
  • 27