- Implement a traversable queue in Java.
-
Clone the repo (or download the zip) for this exercise, which you can find here.
-
Start IntelliJ, go to
File -> Open..., and select the cloned/downloaded folder. -
If at the top it says "Project JDK is not defined", click "Setup JDK" on the top right, and select the JDK version you have installed on your machine.
-
To get the unit tests to work, open
QueueTest.javaand add JUnit to the classpath:- Just click "OK" on the resulting dialogue window and all the test-related red squigglies should disappear.
Question: you are storing integer values in a stack. You want to know something about the data, for example "what is the largest (or smallest) value?", or "is 123 somewhere in the stack", or maybe you just want to output the current stack values.
Options:
-
Pop the elements of the stack and perform the check. Problem: the stack is empty at the end of this, what if we still needed those values in stack. Pushing them back will invert the order unless we are careful.
-
We can add
min,max,find, etc... to theStack<T>class.⚠️ Problem: most of these operations are type-dependant, for exampleminandmaxonly exists forComparabletypes. -
Write a "getter" for the array
elements.⚠️ Problem: direct access to the array might mean the caller breaks LIFO. -
Write a
toArraythat will return a copy of the current array elements.⚠️ Problem: allocating an array takes time and memory. -
Add methods to the
Stack<T>class that return each element in the stack, one by one.
We can think of a traversal as "scanning" a collection.
Taking a look a the Range class first will give you an idea about how to implement Traversable for Queue. A range is simply a low integer and a high integer. Notice that there is *no array in this class, only two numbers. We can use the Range class like this:
Range range = new Range(1, 5);
range.reset();
while (range.hasNext()) {
int nextInt = range.next();
System.out.println(nextInt);
}Internally, Range is not looping over an array. Rather, it is incrementing its own tracker variable which starts at low, and gets incremented every time next() is called.
The behaviour should be similar for Queue where some sort of tracker/traversal/cursor variable will index the queue's array.
Using the class IntQueue (rename it to Queue for this exercise) you developed in the last exercise, or using the starter Queue class included in this exercise:
- Have
Queueimplement theTraversableinterface. - You should have some kind of
traversalmember variable that will point to the current position of the traversal.- Think about where
traversalshould start whenreset()is called. - Think about what value
next()should return and how that will affecttraversal. - Think about what condition(s) you need to have for
hasNext()based on the value oftraversal.
- Think about where
- Pass the unit tests in
TestTraversable.


