Search code examples
javacollectionsarraydeque

ArrayDeque<>(int capacity) - what's the difference between Scanner.nextInt() == 4 and (int) 4?


The task is to write a program that reads numbers and stores them to a deque.

Sample Input is: 4 1 2 3 4 Sample Output: 4 2 1 3

An even number should be added as the first element, an odd number - as the last. After, the program must output all elements from the first to the last.

Here is my piece of code:

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

public class Main {    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Deque<Integer> deque = new ArrayDeque<>(sc.nextInt());

        while (sc.hasNext()) {
            int nextInt = sc.nextInt();
            if (nextInt % 2 == 0) {
                deque.addFirst(nextInt);
            } else deque.addLast(nextInt);
        }

        for (int elt : deque) {
            System.out.println(elt);
        }
    } 
}

Sample Output: 4 2 1 3

It works fine, it's correct. BUT!

Let's rewrite

Deque<Integer> deque = new ArrayDeque<>(sc.nextInt()) 

as

Deque<Integer> deque = new ArrayDeque<>(4)

For this one, sample output is: 4 2 4 1 3 . i.e. it's incorrect.

Why inputing the same capacity different way gives such different results?


Solution

  • This does not have much to do with how you pass the capacity. It has more to do with how many times Scanner.nextInt is called inside the loop.

    Because there are always 5 inputs and the first input is always the size, if you do

    Deque<Integer> deque = new ArrayDeque<>(sc.nextInt()) 
    

    sc.nextInt will be called 5 times in total (because you have 5 inputs), 4 times inside the loop and 1 time in the line above, and so 4 numbers will be added to the Deque. This is correct.

    If you did this however:

    Deque<Integer> deque = new ArrayDeque<>(4)
    

    sc.nextInt will be called 5 times inside the loop, and so 5 numbers will be added to the Deque. But the first number actually shouldn't be added to the Deque, because it is the size, hence producing the wrong output.

    ArrayDeque is resizable so you don't actually need to specify the size and your code will still work.

    You can ignore the first input by calling sc.nextInt before the loop:

    sc.nextInt();
    while (sc.hasNextInt()) {
       ...