Generic Linked List help. *Cannot convert from Object to type T
Code:
public class LinkedList<T> {
public class Node<T>
{
T contents;
Node next;
}
Node head, tail;
public LinkedList()
{
head = new Node();
tail = new Node();
head.next =tail;
tail.next = null;
}
public void addEnd(T element){
Node newNode = new Node();
newNode.contents = element;
newNode.next = head.next;
head.next = newNode;
}
public void addAt(int i, T element)
{
Node current = head;
while(i>0){
current = current.next;
i--;
}
Node newNode = new Node();
newNode.contents = element;
newNode.next=current.next;
current.next = newNode;
}
public T get(int i)
{
Node current = head;
while(i>0)
{
current = current.next;
i--;
}
return current.next.contents;
}
public T removeAndReturn(int i)
{
Node current = head;
while(i>0){
current = current.next;
i--;
}
return current.next.contents;
current.next = current.next.next;
}
public String toString()
{
StringBuilder S = new StringBuilder("");
Node current = head;
while(current != tail)
{
S.append(current.contents.toString() + " ");
current = current.next;
}
return S.toString();
}
}
So here is my linked list class. Not sure what the problem is but when i try and return the contents in getAt(int i) and removeAndReturn(int i) it is telling me that I cannot convert from an Object to type T. Not sure if i am just missing some syntax or what but any help would be appreciated. Any other errors you spot feel free to point out.
Thanks in advance,
MoozicFarm
Re: Generic Linked List help. *Cannot convert from Object to type T
Each element in a LikedList shoud have a reference to the next and to the previous element (except the first and the last element) of type Node. further you should have a other class that have the members first, last current of type Node and a member size of type int. This class shold have a method add(T), getSize() and so on to organize and administer your elements in the list.
Re: Generic Linked List help. *Cannot convert from Object to type T
You need to add lots of <T> to the required place in the code.
Re: Generic Linked List help. *Cannot convert from Object to type T
Quote:
Originally Posted by
Norm
You need to add lots of <T> to the required place in the code.
Where do these <T>'s go? Can you show me with the removeAndReplace() method? I am having trouble figuring this out and I do not know why.
Re: Generic Linked List help. *Cannot convert from Object to type T
One spot would be Node definitions.
Re: Generic Linked List help. *Cannot convert from Object to type T
I'm still not following you!
Re: Generic Linked List help. *Cannot convert from Object to type T
You have define lots of Node variables without using generics. Change those definitions to use generics.