pradeep
pradeep

Reputation: 69

Getting error during compiling java program

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

Upvotes: 1

Views: 281

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69339

Because your LinkedStackIterator class is generic, when it refers to Item it means a different type to the Item used in your outer classes. One solution is to change LinkedStackIterator so it is not generic, i.e. change:

class LinkedStackIterator<Item> implements Iterator<Item>{

to

class LinkedStackIterator implements Iterator<Item>{

Side note: it can be quite confusing to Java programmers to see generic type variables given meaningful names like Item. You may wish to consider renaming this to something more expected like T.

Upvotes: 1

Related Questions