Jon Doe
Jon Doe

Reputation: 13

How do I implement generics <E> in a linked List?

I have been trying to create a linked list that uses generics to return a data type of the user's choosing. The problem is that my method public E get(int sub) is not recognizing my return cursor.contents as a type E generic.

public E get(int sub)
{
    Node cursor = head; //start at the beginning of linked list. 

    for (int c = 1; c <= sub; c++)
    {
        cursor = cursor.next; //move forward by one. 
    }

    return cursor.contents;//return the element that the cursor landed on. 
}


 public class Node <E>
{
        public E contents; 
    @SuppressWarnings("rawtypes")
    public Node next = null; //points to the next node
    //a method has no return type and has the same name as the class
    public Node(E element)
    {
        this.contents = element; 
    }
}

as I have shown above the contents parameter is declared as type E in the Node, but the get method will not recognize cursor.contents as a proper return type.

The system recomments that I either change the return type to Object, which is not an option. Or I change contents to a type E which has already been done, but it still gives me a compilation error.

Upvotes: 1

Views: 231

Answers (4)

Ron
Ron

Reputation: 1508

In your method

public E get(int sub)

You initialize a cursor as a Node instead of Node<E>.

Node cursor = head; //start at the beginning of linked list. 

This will cause the element type to be Object which is what you get when you write

return cursor.contents;

To Solve:

Either use a Node<E> or explicitly cast the return to E

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

That's because you need to change it to:

public E get(int sub)
{
    Node<E> cursor = head; //you forgot the generics here

    for (int c = 1; c <= sub; c++)
    {
        cursor = cursor.next; 
    }

    return cursor.contents;
}


 public class Node <E>
{
    public E contents; 
    public Node<E> next = null; //you also even suppressed the raw type here

    public Node(E element)
    {
        this.contents = element; 
    }
}

Upvotes: 1

1337joe
1337joe

Reputation: 2357

You're not setting the generic type on the declaration of your Node cursor variable. What happens when you change that to Node<E> cursor.

Also, you're not providing context of the linked list class itself - that's where the generic <E> should be declared.

Upvotes: 1

gengkev
gengkev

Reputation: 1959

Are these part of a class with a typed parameter, such as MyLinkedList<E>? The problem may be that you added a <E> type parameter to the Node class as well, which may refer to a different class E that is not necessarily the same E referenced by the outer class. Try changing Node <E> to Node.and see if it works.

Upvotes: 0

Related Questions