I have below two classes
import java.util.*;
public interface Stack<Item> extends Iterable<Item>{
void push(Item item);
Item pop();
boolean isEmpty();
int size();
Iterator<Item> iterator();
}
Second class is the :
import java.util.*;
public class LinkedStack<Item> implements Stack<Item>{
private Node head;
private int size;
private class Node{
Item item;
Node next;
public Node(Item item){
this.item = item;
}
public Node(Item item, Node next){
this.item = item;
this.next = next;
}
}
public boolean isEmpty(){
return(head == null);
}
public int size(){
return size;
}
public void push(Item item){
head = new Node(item,head);
size++;
}
public Item pop(){
Item item = head.item;
head = head.next;
size--;
return item;
}
public Iterator<Item> iterator(){
return new LinkedStackIterator<Item>();
}
class LinkedStackIterator<Item> implements Iterator<Item>{
private Node current = head;
public boolean hasNext(){
return current != null;
}
public Item next(){
Item return_item = current.item;
current = current.next;
return return_item;
}
public void remove(){};
}
}
I am getting typecast error in method public Item next():
Item return_item = current.item;
If I write above line as
Item return_item = (Item) current.item;
It works fine. Can anybody suggest the reason?
I am getting below compilation error:
LinkedStack.java:57: error: incompatible types Item return_item = current.item; ^ required: Item#2 found: Item#1 where Item#1,Item#2 are type-variables: Item#1 extends Object declared in class LinkedStack Item#2 extends Object declared in class LinkedStack.LinkedStackIterator 1 error
current.item?Itemyou won't need to cast it. Look at that class or its documentation to see what type it returns. Check also ifItemimplements any interface. There may be the answer.Itemtypes. You need to either makeNodegeneric or makeLinkedStackIteratornot generic. My vote is to makeNodegeneric (and also make it static).