David
David

Reputation: 7456

Incompatible types using generics

I'm implementing a LinkedList Stack implementation using Generics in Java as practice. I'm getting an error, and want to know why I am getting it as it is unclear to me.

The error:

Error: /Path/To/Code/Java/MyLinkedList.java:64: incompatible types
found: Item
required: Item

The code (it occurs in the Next() method of ListIterator towards the end. There are comments by it.):

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyLinkedList<Item> implements Iterable<Item> {
    private Node first;
    private int N; //size

    private class Node {
        private Node next;
        private Item item;

        private Node(Item item, Node next) {
            this.item = item;
            this.next = next;
        }

    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return this.first == null;
    }

    public void push(Item data) {
        Node oldfirst = this.first;
        this.first = new Node(data, first);
        this.N++;
    }

    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Underflow");
        Item item = this.first.item;
        this.first = this.first.next;
        this.N--;
        return item;
    }

    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Underflow");
        return first.item;
    }

    public String toString() {
       StringBuilder list = new StringBuilder();
        for ( Item item : this) {
            list.append(item + " ");    
        }

        return list.toString();
    }

    public Iterator<Item> iterator() { return new ListIterator(); }

    private class ListIterator<Item> implements Iterator<Item> {
       private Node current = first;
       public boolean hasNext() { return current != null; }
       public void remove() { System.out.println("Can't do dis, nigga"); }

       public Item next() {
            if (!hasNext()) throw new NoSuchElementException();

            //The line in question:
            Item item = current.item;
            //I managed to fix it if I do: Item item = (Item) current.item;
            //Why is that necessary?


            current = current.next; 
            return item;
       }
   }    
}

Upvotes: 2

Views: 699

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213263

You have declared Item as type parameters in both your top-level class and the inner class. So, the Item in MyLinkedList<Item> is different from that in ListIterator<Item>, and hence are incompatible. You can just make your ListIterator class non-generic:

private class ListIterator implements Iterator<Item>

...and you should be fine.

Also, I would suggest to change the type parameter Item to some single letter like E, to avoid getting it confused to some actual class. As per convention, type parameters should be single upper-case letters.

Upvotes: 6

Related Questions