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.
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;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments