views:

90

answers:

2

For a CS class I am writing a linked list implementation of a linked list interface created by my professor. The assignment requires us to use generics for the list. What I have created, I think, is pretty standard.

public class MyLinkedList<T> implements ADTListInterface {
    ...
    private class Node<T> {
        Node<T> head;
        Node<T> prev;
        public Node(int max) {

        ...

        }

        public void shift() {
            ...
            Node<T> newNode = new Node<T>(this.max);
            newNode.prev = head.prev;
            ...
        }

    }

    ...

}

At compile time following error is generated:

MyLinkedList.java:111: incompatible types
   found   : MyLinkedList<T>.Node<T>
   required: MyLinkedList<T>.Node<T>
newNode.prev = head.prev;

This error has me very confused. Can anyone explain to me what the issue is?

+3  A: 

Here is probably the problem:

private class Node<T> {

The <T> is causing extra problems. Because Node is an inner class, it doesn't need to declare its generic type again.

You should declare the Node class like below:

public class MyLinkedList<T> implements ADTListInterface {
...
private class Node {
    Node head;
    Node prev;
    public Node(int max) {

    ...
}
jjnguy
Problem solved, thanks!
Hurpe
@Hurpe, glad to help.
jjnguy
A: 

The question is not nice to read and you did not post your teacher's interface.

But, here is a little linked list I've implemented myself. Maybe it'll help you.

public class MyLinkedList<T> {
Node<T> head;

MyLinkedList() {
    head = new Node<T>();
    head.next = null;
}

public class Node<E> {
    E value;
    Node<E> next;

    Node(E value) {
        this.value = value;
        next = null;
    }

    Node() {
        next = null;
    }
}

public void add(T value) {
    Node<T> n = new Node<T>(value);

    Node<T> last = head;
    while (last.next != null) {
        last = last.next;
    }
    last.next = n;
}


}
pablosaraiva
The node class can't use <T> for generics again because one hides the other. You have to user another letter. I used <E> here. Also, you still have to implement other methods like size and get.
pablosaraiva
Thanks for the help. I didn't think it would be necessary to show the interface because the question was regarding java syntax rather than linked list implementation. Because a linked list implementation is provided in the class text, this linked list assignment does not require a standard linked list. Instead, objects in the list are stored in arrays of size 'max' which are linked together.
Hurpe