Reputation: 21
I am trying to implement an iterate method to my linked list to make it more readable and more compact since it is used more than once. My problem with the code I assume is not properly understanding Java generics in terms of method declaration. This is the error I'm getting:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method iterate(Nodes<T extends Nodes<T>>) in the type LinkedList<T> is not applicable for the arguments (Nodes<T>)
I tried messing around with expected datatypes and arguments but couldn't figure out what is the problem exactly. I checked some other questions but couldn't necessarily find what I asked for or maybe couldn't understand the explanations.
public class LinkedList<T> extends ListTemplate<T>
{
Nodes<T> head;
Nodes<T> tail;
//declaration of method
private <T extends Nodes<T>> Nodes<T> iterate(Nodes<T> head)
{
Nodes<T>iterate=head;
while(iterate.getNext()!=null)
{
iterate=iterate.getNext();
}
return iterate;
}
//the method call
public void Enqueue(T data)
{
Nodes<T>new_node=new Nodes<T>(data);
//head is set for null when list is empty
if(head==null)
{
//if the list is empty both head and tail will box new_node
head=new_node;
tail=new_node;
}
//if we insert something to list head wont be null
else if(head!=null)
{
tail=iterate(head);
tail.setNext(new_node);
}
}
The code works when I don't try to make a separate method and implement in code. The expected result making this method iterate through the list of nodes I provided and return the last node. I am not sure about my mistake, but probably a declaration is problematic.
Upvotes: 1
Views: 88
Reputation: 86411
You're saying that T is both the type of the content of a node, and the type of the returned Nodes object.
private <T extends Nodes<T>> Nodes<T> iterate(Nodes<T> head)
You could fix by saying this instead:
private Nodes<T> iterate(Nodes<T> head)
Upvotes: 0
Reputation: 178263
With this line:
private <T extends Nodes<T>> Nodes<T> iterate(Nodes<T> head)
You're declaring the iterate
method to be generic, with its own T
type parameter, which is different from the class LinkedList
's type parameter T
.
Like the Enqueue
method (which would normally be spelled in lowercase as enqueue
), the iterate
method can simply use the class-scoped T
defined already. Remove the T
declaration on the iterate
method:
private Nodes<T> iterate(Nodes<T> head)
Upvotes: 2