Implementing Queue in Java but cannot override the iterator() method - java

I am trying to develop my knowledge of the Queue interface by implementing it in my own "MyQueue" class. However, I want to override the iterator() method. Since I can't implement both the Iterator and Queue interfaces at the same time, I am at a loss.
On my iterator() method Eclipse is giving me the error, cannot convert from MyQueue<E>.QueueIterator to Iterator<E> when I mouse over the red underline below the words new QueueIterator().
Also, when I try to implement my "QueueIterator" inner class, Eclipse gives me the error, syntax error on token "class", # expected when I mouse over the red underline below the word class.
In the code examples below, I have removed all methods that have nothing to do with my question. I know I have to implement these methods to implement Queue. I'm just trying to make the problem clearer.
How can I override the iterator() method?
MyQueue class:
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
* A custom queue class. Uses a singly-linked list.
*/
public class MyQueue<E> implements Queue {
// the top of the queue
private Node<E> first;
private int size;
/**
* Creates new myQueue object
*/
public MyQueue() {
first = null;
current = null;
size = 0;
}
#Override
public Iterator<E> iterator() {
return new QueueIterator();
}
/**
* Holds Objects and points to the next one.
*
*/
private class Node<E> {
private E data;
private Node<E> next;
/**
* Creates a Node object
* #param data The Object to be held by the Node
*/
Node(E data) {
this.data = data;
this.next = null;
}
private Node<E> getNext() {
return this.next;
}
private E getData() {
return this.data;
}
}
/**
* Iterator implementation
*/
private class QueueIterator() {
private Node<E> curNode;
public QueueIterator() {
curNode = null;
}
public boolean hasNext() {
if(curNode == null && first != null) {
return true;
} else if (curNode.getNext() != null) {
return true;
} else {
return false;
}
}
public E next() {
if(curNode == null && first != null) {
curNode = first;
return curNode.getData();
}
if(!hasNext()) {
throw new NoSuchElementException();
}
curNode = curNode.getNext();
return curNode.getData();
}
}

QueueIterator needs to implement Iterator<E>.
You shouldn't have the parentheses on this line:
private class QueueIterator() {
It should be just:
private class QueueIterator {
Actually:
private class QueueIterator implements Iterator<E> {

Related

Type T is not a valide Substitute for the bounded Parameter `<T extends Collection<?>>

package einfuehrung.knodenUndListeKopie;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class List<T> {
private class ListIterator<K> implements Iterator<T> {
private Node<T> node = null;
public ListIterator() {
node = head;
}
#Override
public boolean hasNext() {
return node.getNext() != null;
}
#Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
node = node.getNext();
T obj = node.getObject();
return obj;
}
}
public Iterator<T> iterator() {
ListIterator<T> iter = new ListIterator<T>();
return iter;
}
private Node<T> head;
public List() {
this.head = new Node<T>();
}
public Node<T> getHead() {
return head;
}
public void setHead(Node<T> head) {
this.head = head;
}
public boolean isEmpty() {
return head.getNext() == null;
}
public void addFirst(T element) {
Node<T> node = new Node<T>();
Node<T> nextNode = head.getNext();
node.setObject(element);
node.setNext(nextNode);
head.setNext(node);
}
public void addLast(T element) {
Node<T> node = new Node<T>();
Node<T> lastNode = head;
while (lastNode.getNext() != null) {
lastNode = lastNode.getNext();
}
lastNode.setNext(node);
node.setNext(null);
node.setObject(element);
}
public Object removeFirst() {
Object solution;
if (isEmpty()) {
solution = null;
}
Node<T> node = head.getNext();
Node<T> nextNode = node.getNext();
solution = node.getObject();
head.setNext(nextNode);
return solution;
}
public Object removeLast() {
Object solution;
if (isEmpty()) {
solution = null;
}
Node<T> beforeLastNode = head;
Node<T> lastNode;
while (beforeLastNode.getNext().getNext() != null) {
beforeLastNode = beforeLastNode.getNext();
}
lastNode = beforeLastNode.getNext();
solution = lastNode.getObject();
beforeLastNode.setNext(null);
return solution;
}
/**
* It does not delete the node, where the element is saved.
*
* #return first element of list
*/
public Object getFirstElement() {
return head.getNext().getObject();
}
}
First above is my List-Class.
package einfuehrung.knodenUndListeKopie;
import java.util.Collection;
public class Node<T extends Collection<?>> {
private Node<T> next;
private T object;
public Node() {
}
public Node(Node<T> next, T object) {
this.next = next;
this.object = object;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
}
public int countAllElements() {
int solution;
solution = object.size();
if (this.next != null) {
solution += this.next.countAllElements();
}
return solution;
}
}
Second Class is my Node-Class.
Problem Description. Everything was fine after i restricted the Parameter T in my Node Class. I had to, because T needed to implement the size-Method. It was necessary for the countAllElements() Method in Node-Class. In my List Class i get the error message : "Type T is not a valide Substitute for the bounded Parameter <T extends Collection<?>> of the type Node<T>. The error message appears everywhere where i use an instance of my object from the type Node<T>.
I hope i did everything Right in this Question by Posting my Code here. Sorry for my case-shift, i live in Germany. I dont know what my Computer does D:.
Edited: Sorry guys, i forgot to Change the title. I adjusted it.
As it stands, you are contradicting yourself: you are saying that your Nodes can contain any T in your List class, but your Node class says they can contain any Collection.
So, you either need to:
Go through all of the Node<T>s in the List class, replacing them with something list Node<Collection<T>>, Node<List<T>> etc
Remove the bound on the type parameter in the Node class, and supply a ToIntFunction<? super T> to the countAllElements method, to allow you to say "this is how you 'count' a T":
public int countAllElements(ToIntFunction<? super T> counter) {
int solution = counter.apply(object);
if (this.next != null) {
solution += this.next.countAllElements(counter);
}
return solution;
}

can not find method from my interface

I created an interface called LLIterator that extends iterator and add two methods to it, when i tried to use it in one of my class, I couldn't compile it. Here is what I got.
my custom interface is like this:
import java.util.Iterator;
public interface LLIterator<T> extends Iterator<T>{
boolean hasNext();
T next();
void remove();
void addBefore(T element);
void addAfter(T element);
}
my linkedlist is like this:
import java.lang.StringBuilder;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ArrayList;
/**
* A class to represent a linked list of nodes.
*/
public class LinkedList<T> implements Iterable<T>{
/** the first node of the list, or null if the list is empty */
private LLNode<T> first;
/** some codes here
#Override
public LLIterator<T> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements LLIterator<T>{
LLNode<T> nodeptr = first;
final LinkedList<T> list = getList();
#Override
public void addBefore(T element){
if(nodeptr == first || list.isEmpty()){
throw new NoSuchElementException();
}
LLNode<T> newnode = new LLNode<T>(element, null);
newnode.setNext(nodeptr);
}
#Override
public void addAfter(T element){
LLNode<T> newnode;
if(nodeptr == first || list.isEmpty()){
newnode = new LLNode<T>(element, null);
list.setFirst(newnode);
}
newnode = new LLNode<T>(element, null);
newnode.setNext(nodeptr.getNext());
nodeptr.setNext(newnode);
}
}
in another class, i used iterator method of the this Linkedlist and called addBefore method, however when I compile it, it shows
cannot find symbol
symbol: method addAfter(WordData)
location: variable iterator of type java.util.Iterator<WordData>
here is part of my another class:
public void addFollowingWord(String word){
Iterator<WordData> iterator = list.iterator();
WordData current = iterator.next();
while(iterator.hasNext()){
if(current.getWord().equals(word)){
current.incrementCount();
}
else if(current.getWord().compareTo(word) < 0){
current = iterator.next();
}
else if(current.getWord().compareTo(word) > 0){
WordData newword = new WordData(word);
iterator.addBefore(newword);
}
}
if(!iterator.hasNext()){
WordData newword = new WordData(word);
iterator.addAfter(newword);
}
}
I'm very confused, did I make any mistake somewhere or I missed something?
You can't access the methods on the custom interface because it's cast as Iterator. Update your iterator() method to return your subinterface:
#Override
public LLIterator<T> iterator() {
return new LinkedListIterator();
}

Iterative approach to BST

these are my fields:
public class BSTSet <E> extends AbstractSet <E> {
// Data fields
private BSTNode root;
private int count = 0;
private Comparator<E> comp; // default comparator
/** Private class for the nodes.
* Has public fields so methods in BSTSet can access fields directly.
*/
private class BSTNode {
// Data fields
public E value;
public BSTNode left = null;
public BSTNode right = null;
// Constructor
public BSTNode(E v) {
value = v;
}
//creates a method called contains so that i can call it later on for my find method
public boolean contains(Object item) {
return contains(item);//root.value.equals(item);
}
public int height() {
return height();
}
}
// Constructors - can either use a default comparator or provide one
public BSTSet() {
comp = new ComparableComparator(); // Declared below
}
public BSTSet(Comparator <E> c) {
comp = c;
}
}
and this is what i am trying to complete:
private class BSTSetIterator implements Iterator<E> {
private Stack<BSTNode> stack = new Stack<BSTNode>();
private BSTNode current = root;
public BSTSetIterator(BSTNode root) {
return new BSTSetIterator();
}
public boolean hasNext() {
boolean hasNext = false;
hasNext = !stack.isEmpty() || current != null;
return hasNext;
}
public E next() {
BSTNode next = null;
while (current != null) {
stack.push(current);
current = current.left;
}
next = stack.pop();
current = next.right;
return next;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
// Comparator for comparable
private class ComparableComparator implements Comparator<E> {
public int compare(E ob1, E ob2) {
return ((Comparable)ob1).compareTo(ob2);
}
}
So far the code fails at lines return new BSTSetIterator(); and return next;. For return next it says that it is the wrong data type to return. How would I go about fixing these methods so that I can iterate through a BST using a Stack?
BSTSetIterator();
This doesn't work, because your constructor expects a root and you didn't pass that parameter. If you have a BSTSet object called 'tree', and you want to create a new iterator, then you should create the iterator this way:
BSTSetIterator iterator = new BSTSetIterator(tree.getRoot());
However, you don't have a getter in your BSTSet class and your root is private. Don't worry, the solution for that problem is to create a public getter inside your BSTSetIterator class, like this:
public BSTNode getRoot()
{
return this.root;
}
Constructors don't return values, this is incorrect:
public BSTSetIterator(BSTNode root) {
return new BSTSetIterator();
}
Instead, write your construtor this way:
public BSTSetIterator(BSTNode root)
{
this.current = root;
}
Also, this definition is incorrect, because root is out of reach:
private BSTNode current = root;
You should have this instead:
private BSTNode current;
As for your other problem,
BSTNode next = null;
means that your variable called 'next' is of BSTNode type.
public E next()
means that your method called next is of E type. as E and BSTNode is not the same, your return:
return next;
is incorrect. I could give you more help, but I have realized you are learning now the language and it's better to let you explore yourself the technology and programming in general, because this way you will become quicker. "Give a man a fish, and you feed him for a day. Teach a man how to fish, and you feed him for a lifetime."

Best implementation of Java Queue?

I am working (in Java) on a recursive image processing algorithm that recursively traverses the pixels of the image, outwards from a center point.
Unfortunately, that causes a Stack Overflow. So I have decided to switch to a Queue-based algorithm.
Now, this is all fine and dandy- but considering the fact that its queue will be analyzing THOUSANDS of pixels in a very short amount of time, while constantly popping and pushing, WITHOUT maintaining a predictable state (It could be anywhere between length 100, and 20000), the queue implementation needs to have significantly fast popping and pushing abilities.
A linked list seems attractive due to its ability to push elements onto itself without rearranging anything else in the list, but in order for it to be fast enough, it would need easy access to both its head, AND its tail (or second-to-last node if it were not doubly-linked). Sadly, I cannot find any information related to the underlying implementation of linked lists in Java, so it's hard to say if a linked list is really the way to go...
This brings me to my question. What would be the best implementation of the Queue interface in Java for what I intend to do? (I do not wish to edit or even access anything other than the head and tail of the queue -- I do not wish to do any sort of rearranging, or anything. On the flip side, I DO intend to do a lot of pushing and popping, and the queue will be changing size quite a bit, so preallocating would be inefficient)
Use:
Queue<Object> queue = new LinkedList<>();
You can use .offer(E e) to append an element to the end of the queue and .poll() to dequeue and retrieve the head (first element) of the queue.
Java defined the interface Queue, the LinkedList provided an implementation.
It also maintains references to the Head and Tail elements, which you can get by .getFirst() and .getLast() respectively.
credit to #Snicolas for suggesting queue interface
If you use LinkedList be careful. If you use it like this:
LinkedList<String> queue = new LinkedList<String>();
then you can violate queue definition, because it is possible to remove other elements than first (there are such methods in LinkedList).
But if you use it like this:
Queue<String> queue = new LinkedList<String>();
it should be ok,as this is heads-up to users that insertions should occur only at the back and deletions only at the front.
You can overcome defective implementation of the Queue interface by extending the LinkedList class to a PureQueue class that throws UnsupportedOperationException of any of the offending methods. Or you can take approach with aggreagation by creating PureQueue with only one field which is type LinkedList object, list, and the only methods will be a default constructor, a copy constructor, isEmpty(), size(), add(E element), remove(), and element(). All those methods should be one-liners, as for example:
/**
* Retrieves and removes the head of this queue.
* The worstTime(n) is constant and averageTime(n) is constant.
*
* #return the head of this queue.
* #throws NoSuchElementException if this queue is empty.
*/
public E remove()
{
return list.removeFirst();
} // method remove()
Check out the Deque interface, which provides for insertions/removals at both ends. LinkedList implements that interface (as mentioned above), but for your use, an ArrayDeque may be better -- you won't incur the cost of constant object allocations for each node. Then again, it may not matter which implementation you use.
Normal polymoprhism goodness comes to play: the beauty of writing against the Deque interface, rather than any specific implementation of it, is that you can very easily switch implementations to test which one performs best. Just change the line with new in it, and the rest of the code stays the same.
It's better to use ArrayDeque instead of LinkedList when implementing Stack and Queue in Java. ArrayDeque is likely to be faster than Stack interface (while Stack is thread-safe) when used as a stack, and faster than LinkedList when used as a queue. Have a look at this link Use ArrayDeque instead of LinkedList or Stack.
If you know the upper bound of possible quantity of items in the queue, circular buffer is faster than LinkedList, as LinkedList creates an object (link) for each item in the queue.
I think you can some up with simple like implementation
package DataStructures;
public class Queue<T> {
private Node<T> root;
public Queue(T value) {
root = new Node<T>(value);
}
public void enque(T value) {
Node<T> node = new Node<T>(value);
node.setNext(root);
root = node;
}
public Node<T> deque() {
Node<T> node = root;
Node<T> previous = null;
while(node.next() != null) {
previous = node;
node = node.next();
}
node = previous.next();
previous.setNext(null);
return node;
}
static class Node<T> {
private T value;
private Node<T> next;
public Node (T value) {
this.value = value;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> next() {
return next;
}
}
}
However, if you still want to use the recursive algorithm, you can change it to be "tail-recursive" which probably is optimized in the JVM to avoid stack overflows.
O(1) access to first and last nodes.
class Queue {
private Node head;
private Node end;
public void enqueue(Integer data){
Node node = new Node(data);
if(this.end == null){
this.head = node;
this.end = this.head;
}
else {
this.end.setNext(node);
this.end = node;
}
}
public void dequeue (){
if (head == end){
end = null;
}
head = this.head.getNext();
}
#Override
public String toString() {
return head.getData().toString();
}
public String deepToString() {
StringBuilder res = new StringBuilder();
res.append(head.getData());
Node cur = head;
while (null != (cur = cur.getNext())){
res.append(" ");
res.append(cur.getData());
}
return res.toString();
}
}
class Node {
private Node next;
private Integer data;
Node(Integer i){
data = i;
}
public Integer getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Here is the Queue Implementation with Iterator and Iterable interface
Queue Size will increase as It gets full
Queue Interface
package com.practice.ds.queue;
import com.practice.ds.queue.exception.QueueException;
public interface QueueInterface<T> {
public boolean empty();
public void enqueue(T item);
public void dequeue() throws QueueException;
public T front() throws QueueException;
public void clear();
}
Custom Exception Class
package com.practice.ds.queue.exception;
public class QueueException extends Exception {
private static final long serialVersionUID = -884127093599336807L;
public QueueException() {
super();
}
public QueueException(String message) {
super(message);
}
public QueueException(Throwable e) {
super(e);
}
public QueueException(String message, Throwable e) {
super(message, e);
}
}
Implementation of Queue
package com.practice.ds.queue;
import java.util.Iterator;
import com.practice.ds.queue.exception.QueueException;
public class Queue<T> implements QueueInterface<T>, Iterable<T> {
private static final int DEFAULT_CAPACITY = 10;
private int current = 0;
private int rear = 0;
private T[] queueArray = null;
private int capacity = 0;
#SuppressWarnings("unchecked")
public Queue() {
capacity = DEFAULT_CAPACITY;
queueArray = (T[]) new Object[DEFAULT_CAPACITY];
rear = 0;
current = 0;
}
#Override
public boolean empty() {
return capacity == current;
}
#Override
public void enqueue(T item) {
if(full())
ensureCapacity();
queueArray[current] = item;
current++;
}
#Override
public void dequeue() throws QueueException {
T dequeuedItem = front();
rear++;
System.out.println("Dequed Item is " + dequeuedItem);
}
#Override
public T front() throws QueueException {
return queueArray[rear];
}
#Override
public void clear() {
for (int i = 0; i < capacity; i++)
queueArray[i] = null;
current = 0;
rear = 0;
}
#SuppressWarnings("unchecked")
private void ensureCapacity() {
if (rear != 0) {
copyElements(queueArray);
} else {
capacity *= 2;
T[] tempQueueArray = (T[]) new Object[capacity];
copyElements(tempQueueArray);
}
current -= rear;
rear = 0;
}
private void copyElements(T[] array) {
for (int i = rear; i < current; i++)
array[i - rear] = queueArray[i];
queueArray = array;
}
#Override
public Iterator<T> iterator() {
return new QueueItearator<T>();
}
public boolean full() {
return current == capacity;
}
private class QueueItearator<T> implements Iterator<T> {
private int index = rear;
#Override
public boolean hasNext() {
return index < current;
}
#SuppressWarnings("unchecked")
#Override
public T next() {
return (T) queueArray[index++];
}
}
}

Compile error with Java generic types

I'm doing a learning exercise and creating my own linked list with an iterator. The class is as follows:
public class LinkedList<T> implements Iterable <T> {
private Node<T> head;
private Node<T> tail;
private int size;
public LinkedList() {
head = new Node<T>();
tail = new Node<T>();
head.setNext(tail);
tail.setPrevious(head);
size = 0;
}
public void append(T element) {
tail.getPrevious().setNext(new Node<T>(element));
tail.getPrevious().getNext().setNext(tail);
tail.getPrevious().getNext().setPrevious(tail.getPrevious());
tail.setPrevious(tail.getPrevious().getNext());
size++;
}
public void prepend(T element) {
head.getNext().setPrevious(new Node<T>(element));
head.getNext().getPrevious().setPrevious(head);
head.getNext().getPrevious().setNext(head.getNext());
head.setNext(head.getNext().getPrevious());
size++;
}
public void remove(Node<T> nodeToRemove) {
if(!isEmpty()) {
nodeToRemove.getPrevious().setNext(nodeToRemove.getNext());
nodeToRemove.getNext().setPrevious(nodeToRemove.getPrevious());
nodeToRemove.setNext(null);
nodeToRemove.setPrevious(null);
nodeToRemove.setElement(null);
nodeToRemove = null;
size--;
}
}
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return size;
}
public Iterator<T> iterator() {
return new Cursor<T>(head);
}
public String toString() {
String result = "";
for(T t : this) {
result += t.toString() + "\n";
}
return result;
}
private final class Cursor<E> implements Iterator<E> {
private Node<E> current;
public <E> Cursor(Node<E> head) {
this.current = current;
}
public boolean hasNext() {
return current.getNext().getNext() != null;
}
public E next() {
current = current.getNext();
return current.getElement();
}
public void remove() {
remove(current);
}
}
}
After doing quite a bit of research it appears a good way to implement the iterator is to do it as an innner class. However, I'm getting a compile error with my remove method in the cursor class. I believe it's because of a type mismatch although the error I'm getting is remove() in LinkedList<T>.Cursor<E> cannot be applied to <Node<E>).
I've wrestled with this for quite some time and I can't understand what is wrong exactly, I would appreciate any insights you may have.
There are a few things wrong:
You have 2 methods called remove. Java thinks you are trying to call remove in the inner Cursor class which takes no parameters. You have to qualify the reference like this:
LinkedList.this.remove(current);
Your inner cursor class is non-static. Non-static inner classes are associated with the outer class instance that created them. Basically, they maintain a parent pointer to the outer class object. This is correct for implementing an iterator, but you need to change how you're using generics. Non-static inner classes can use the type parameters of their parent class. This means you can change your iterator definition to:
private final class Cursor implements Iterator<T>
and it will automatically use the <T> from LinkedList.
this.current = current; should probably be this.current = head;
Why does hasNext call getNext() twice?
Hope that helps.

Categories

Resources