Solution to 2d33: Reversed order of input
See code at solutions/code/tutorialquestions/question2d33
ReversedOrderOfInputArray.java shows how this problem can be solved using an array in the case where the maximum input size is 100. Note that the number 100 is represented as a local constant.
Check that you understand how the BufferedReader
class is used in this
example. (The beauty of encapsulation is that you don't need to worry about how
BufferedReader
works, you just need to know how to use it.)
Notice that the condition for the while
loop is:
line != null && counter < max
That is, the loop exits when the end of the input is reached or the maximum input size is reached.
ReversedOrderOfInputStack.java shows how a Deque
can be used to
eliminate the need for the input size to be bounded. Of course, the input size is still
bounded: by the amount of memory available to the Java Virtual Machine!
Check that you are comfortable with the way generics have been used to construct a
Deque
of strings. The line:
Deque<String> dq = new ArrayDeque<>();
might look a bit mysterious at first. You will be able to fully comprehend this in due course when
we cover interfaces. Until then: Deque
is an interface that is implemented
by ArrayDeque
. Thus we specify Deque<String>
as the apparent type for dq
,
but construct (using new
) an instance of ArrayDeque<String>
, which is the actual type
of dq
.