Error reversing queue in recursive Java method - java

I am trying to write a recursive method to reverse all elements in a queue.
In an abstract class myQueue which implements Queue< T > interface is my reverse method:
public void reverse() {
T temp = dequeue();
Queue<T> bufferQueue = new Queue<T>();
if(!(temp == null)){
bufferQueue.enqueue(temp);
}
if(!(isEmpty())) {
reverse();
}else{
while(!(bufferQueue.isEmpty())){
Queue.enqueue(bufferQueue.dequeue);
}
}
}
The interface Queue< T > has the following methods which are complete(and implicitly do as defined):
public boolean isEmpty();
public int size();
public void enqueue(T e);
public T dequeue();
public T front();
My goal:
In my reverse method, I am aiming to constantly dequeue (remove first element) from my Original Queue recursively till my queue is empty. Every time I dequeue I will place that object in a temporary Queue. When my queue is empty, than I do enqueue from my temp queue back in to my original Queue.
My first problem is defining a new temporary queue, in my case bufferQueue. I get the following:
1. ERROR at solution.java (at line 12)
Queue<T> bufferQueue = new Queue<T>();
^^^^^
Cannot instantiate the type Queue<T>

Queue is an interface. You can't create an instance of an interface.
Check the JavaDoc for Queue and choose a Class that implements Queue instead:
https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
What you are trying to accomplish is surprisingly simple and doesn't require recursion at all, just the available methods on a concrete class, like ArrayDeque + your custom reverse method. Also, you don't need the intermediate bufferQueue. This should work nicely:
public class MyQueue<T> extends ArrayDeque<T>{
public void reverse() {
T[] contents = toArray(T[]);
clear();
if(contents != null){
for(int i = contents.length-1; i >= 0; i--){
add(contents[i]);
}
}
}
}

You need to have a concrete type there not T, T is not possible when isntantiating.

Related

What Iterator.next() method do inside a for statement when used with java.util.Queue?

For example:
public class Test {
public static void main(String[] args) {
Queue<String> names = new LinkedList<>(Arrays.asList("First", "Middle", "Last"));
System.out.println("Queue before the loop: " + names);
System.out.println("Printing loop...");
for (Iterator<String> i = names.iterator(); i.hasNext();) {
String name = i.next();
System.out.println(name);
}
System.out.println("Queue after the loop: " + names);
}
}
Output:
Queue before the loop: [First, Middle, Last]
Printing loop...
First
Middle
Last
Queue after the loop: [First, Middle, Last]
I know how the next() method traverse the LinkedList. But when it is called on a Queue.iterator() like, i.next() what does it do? As you can see from the output it haven't removed any element from the queue. which I thought would be the case, since Queue only have remove()/poll().
Iterator is simply used to iterate over a Collection. In this case, you could have used a for-each for the same result:
for(String name : names){
System.out.println(name);
}
Based on your question however, I assume you want to iterate over the Queue, popping and printing each item in FIFO order (hence the use of your LinkedList). In that case, you may simply want to loop names.size() amount of times, and calling .remove() to pop an item each iteration, like this:
for(int n = names.size(); n > 0; n--){
String name = names.remove();
System.out.println(name);
}
Output:
Queue before the loop: [First, Middle, Last]
Printing loop...
First
Middle
Last
Queue after the loop: []
Try it online.
EDIT: To explain a bit more of what's going on for the .iterator():
If we look at the source code of the Iterator, we can see it's an interface. Each Collection-implementation will have its own individual Iterator implementation.
Looking at the source code of the Queue, the iterator() method is this:
/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
*
* #return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Item> {
private Node current = first; // node containing current item
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
As you can see, it stores the Node first of Queue as its current when the ListIterator is created in the iterator() method.
In the actual next()-method, it uses neither the remove() nor poll() methods of the Queue (nor get()..), so the items aren't actually popped. Instead, it simply stores the current Node temporarily with Item item = current.item; then updates the current Node to the next one with current = current.next; after which it will return that temporary item.
Since names is a LinkedList object and LinkedList does't have
any iterator() method in it, names.iterator() would call
that method in
AbstractSequentialList
(immediate super class of LinkedList).
However, by tracking the call stack (can be done easily through a GUI debugger of any decent java IDE) when initializing i = names.iterator() one can easily see it calls the method listIterator(0) method here. Eventhough AbstractList has it's own implementation of listIterator(int index), LinkedList has overriden that same method ;
Segment of LinkedList.java :
package java.util;
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
*
* (code contraction...)
*
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
Hence, obviously names.iterator() would return an object through return new ListItr(index), which is an inner class of LinkedList.
Now we can clearly see when calling i.next(), it actually calls the next() method in the inner class ListItr. Also it uses the class variable;
private Node<E> next;
to track, to where the iterator is pointing next.
This comes into play when considering the performance of the enhanced for loop.
Segment of Oracle docs for enhance-for-loops :
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt TargetType Identifier = (TargetType) #i.next();
Statement
}
As you can see this uses the #i.next() method and since names(in the original question's example) is a variable of type Queue, one can in-the-dark assume #i.next() in the enhanced-for-loop uses this implementation which is in AbstractList and it questionably uses some get(int index) method, hence poor performance (a poor,unfortunate guy like me, did the same deduction and caught up in a hay-stack of code. LOL).
On that false deduction I asked this question in this forum and after digging deeper for several days, now I can see there are no any performance reduction(not that I know of) when using an enhanced-for-loop to iterate over a LinkedList object due to the fact,
that iterator object(#i) uses a variable Node<E> next to keep the reference to the next object in-order to use in the enhanced-for-loop 's next iteration.

Solution: Iterator which doesn't know if it has a next element

I wrote an iterator, which returns subgraphs of a fixed size of another given undirected simple graph.
It maintains an internal graph which is the currently calculated subgraph and has private stacks and lists from which it calculates the next subgraph.
It is not possible to know if the iterator can return another element, because maybe the algorithm terminates when trying to find the next subgraph.
In this design, the pattern of next() and hasNext() which Java offers doesn't work out. I currently wrote my own Interface BlindIterator with the following abstract methods:
/**
* #return True iff the current element is a valid return.
*/
public boolean hasCurrent();
/**
* #return Returns the current element, but does NOT generate the next element. This method can be called
* as often as wanted, without any side-effects.
*/
public T getCurrent();
/**Generates the next element, which can then be retrieved with getCurrent(). This method thus only provides
* this side-effect. If it is called while the current element is invalid, it may produce and exception,
* depending on the implementation on the iterator.
*/
public void generateNext();
Is this a common pattern and are there better designs than mine?
I believe what you have created is equivalent to the Iterator interface. Here is an implementation of Iterator using your BlindIterator:
class BlindIteratorIterator<T> implements Iterator<T> {
private BlindIterator<T> iterator;
public BlindIteratorIterator(BlindIterator<T> iterator) {
this.iterator = iterator;
iterator.generateNext();
}
#Override
public boolean hasNext() {
return iterator.hasCurrent();
}
#Override
public T next() {
T next = iterator.getCurrent();
iterator.generateNext();
return next;
}
}
You implement the iterator to preload/cache the next element (subgraph).
For example, if your elements are sourced from a Supplier, where the only method is a get() method that returns the next element, or null if no more elements are available, you would implement the Iterator like this:
public final class SupplierIterator<E> implements Iterator<E> {
private final Supplier<E> supplier;
private E next;
SupplierIterator(Supplier<E> supplier) {
this.supplier = supplier;
this.next = supplier.get(); // cache first (preload)
}
#Override
public boolean hasNext() {
return (this.next != null);
}
#Override
public E next() {
if (this.next == null)
throw new NoSuchElementException();
E elem = this.next;
this.next = supplier.get(); // cache next
return elem;
}
}
Answer by Joni has a good Iterator implementation that can use your intended BlindIterator as the source of elements.
Since you only invented the BlindIterator to work around your perceived limitations of Iterator, I'd recommend not doing that. Make the iterator implementation call the underlying "generate" logic directly.

Why is a Queue<Integer> returning an Iterable<Integer> here?

Context:
I am reading chapter 4 of Sedgewick & Wayne's Algorithms.
This code example is a code example of "Depth-first search vertex ordering in a digraph".
public class DepthFirstOrder
{
private boolean[] marked;
private Queue<Integer> pre; // vertices in preorder
private Queue<Integer> post; // vertices in postorder
private Stack<Integer> reversePost; // vertices in reverse postorder
public DepthFirstOrder(Digraph G)
{
pre = new Queue<Integer>();
post = new Queue<Integer>();
reversePost = new Stack<Integer>();
marked = new boolean[G.V()];
for (int v = 0; v < G.V(); v++)
if (!marked[v]) dfs(G, v);
}
private void dfs(Digraph G, int v)
{
pre.enqueue(v);
marked[v] = true;
for (int w : G.adj(v))
if (!marked[w])
dfs(G, w);
post.enqueue(v);
reversePost.push(v);
}
public Iterable<Integer> pre()
{ return pre; }
public Iterable<Integer> post()
{ return post; }
public Iterable<Integer> reversePost()
{ return reversePost; }
}
My question is why the Queues are returned as Iterables in their respective methods for retrieval.
I get what the code does otherwise, but what I don't understand is why pre, post and reversePost are returning an Iterable here while they are Queues?
I understand what the Iterable interface normally does, and that a Queue is also an Iterable because Collection implements Iterable.
I don't understand however, why this implementation is returning the Queues as Iterables.
It's so that the external interface only promises that those are Iterable, not specifically that they're Queues. This means:
The implementation can change without affecting the interface the class provides.
Users of the returned queues can only rely on them being Iterables, they can't assume they're Queues, specifically. (Which amongst other things means the can't use state-mutating features Queue provides beyond the one [remove] that Iterable does — not without casting them, which would be a Bad Thing™ because all that the class guarantees is that they're Iterables, not that they're Queues.)
A more defensive class might insert a facade between the actual Queue and the returned object to defend against poorly-written code doing #2 above, but of course, there's a cost there.

Java look at elements in queue

So I'm making a search algorithm. I'm using a queue to store all of my objects
This is how I initialised it
Queue<Node> queue = new LinkedList<Node>();
I want to compare a variable in each object and order to queue. My plan is to use a for loop to compare the first object with each of the other objects and whichever object has the lowest variable is sent to the front of the queue. Then move onto the next object and repeat the process. My issue is I'm not sure how to retrieve an object from the queue that isn't the first object in the queue....
You could do a for loop through the Queue:
for (Node n : queue) {
do stuff with n
}
However, you aren't going to be able to remove items from the middle of the queue. Might I suggest a structure like an ArrayList?
In my opinion the best way is to use PriorityQueue. You can specify implementation of Comparator interface that will impose how elements should be sorted inside of queue.
Here is an example:
Let's say that this is your Node class:
public class Node {
// this field will be used to sort in queue
private int value;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
#Override
public String toString() {
return "My value is: " + value;
}
}
And here is example of adding Nodes into queue:
import java.util.PriorityQueue;
import java.util.Random;
public class QueueExample {
public static void main(String[] args) {
Random r = new Random();
// Priority queue with custom comparator
PriorityQueue<Node> queue = new PriorityQueue<Node>(10, new SampleNodeComparator());
// adding 100 nodes with random value
for(int i = 0; i < 100; ++i) {
queue.add( new Node(r.nextInt(1000)));
}
// nodes will be removed from queue in order given by comparator
while(queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
And the most important part - implementation of our custom comparator
import java.util.Comparator;
// our comparator needs to implements Comparator interface
public class SampleNodeComparator implements Comparator<Node> {
#Override
public int compare(Node o1, Node o2) {
/*
value that should be return from compare method should follow rules:
if o1 == o2 - return 0
if o1 > o2 - return any positive value
if o1 < 02 - return any negative value
*/
return o1.getValue() - o2.getValue();
}
}
When you run main method from QueueExample class you will see on console that values are removed from queue sorted by Node.value value.
Use Queue<E>#peek () to retrieve an object without removing it.
Some example code:
import java.util.*;
class Example {
public static void main (String[] args) throws Exception {
Queue<String> list = new PriorityQueue<>();
{ // Initialize the Queue
list.add ("Hello ");
list.add ("Mrs. ");
list.add ("DoubtFire! ");
}
System.out.println (list);
// Iterating through the Queue
String element;
while ( (element = list.peek()) != null) {
if (element.equals ("Mrs. ")) {
System.out.println ("\"Mrs\" found!");
}
System.out.println (element);
list.remove (element);
}
System.out.println (list); // Empty by now...
}
}
Output:
[DoubtFire! , Mrs. , Hello ]
DoubtFire!
Hello
"Mrs" found!
Mrs.
[]
Queue interface does not guarantee any particular order while iterating or polling so theoretically this task is impossible to implement with Queue.
Seeing your response to my comment, I think that in your case, you should use the PriorityQueue because it does what you need without needing you to reinvent the wheel, which is usually not recommended.
By default, the priority queue will use the default implementation of the compareTo method. Assuming that you have a composite type, you have two options:
You can make your custom class implement the Comparabale interface and have your sorting logic there.
Alternatively, you could pass your own comparator:
PriorityQueue<..> p = new PriorityQueue<..>(5, new Comparator<..>()
{
#override
public int compare(.. type1, .. type2)
{
//comparison logic done here.
}
}
You can take a look at this short tutorial for more information.

Iterating through elements of a data structure instead of Collection

My problem is this: I have an iterator class which is supposed to iterate through elements in a given data structure, <E> let's say, but what I have managed to accomplish is that when I pass in the data structure it will iterate the data structure itself.
ie. DynamicIterator it = new DynamicIterator(da);
say da is an array the output will be [1,2,3,4,5,6] instead of 1,2,3,4,5,6
My issue is, more than anything, understanding the generally accepted practice for dealing with this more than the issue itself.
edit for code:
public class X<E>
{
private final E[] rray;
private int currentIndex = 0;
public X(E... a)
{
//if the incoming array is null, don't start
if(a == null)
{
System.out.println("Array is null");
System.exit(1);
}
//set the temp array (rray) to the incoming array (a)
this.rray = a;
}
//hasNext element?
public boolean hasNext()
{
return rray.length > currentIndex;
}
//next element (depends on hasNext())
public E next()
{
if (!hasNext())
{
System.out.println("Element doesn't exist, done");
System.exit(1);
}
return rray[currentIndex++];
}
//return array
public E[] access()
{
return rray;
}
}
You won't be able to do this with a completely generic parameter <E> - how would you iterate through a Throwable, for example? What your class X does at the moment is accept any number of objects in its constructor, and then simply returns each of those objects in turn.
If you restricted the bounds of the objects passed in to implement e.g. Iterable, then you can actually start to "look inside" them and return their contents:
public class X<E> {
private final Iterator<E> it;
public X(Iterable<E> a) {
it = a.iterator();
}
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
}
Although this doesn't really accomplish anything different to just using a.iterator() directly instead of an instance of X...

Categories

Resources