Hi I am writing a linked list data type. I have an inner class node that I use to store the elements and the successors. I am currently having trouble with my getElement in my node and my get method in my list.
this is my getElement in the node
public E getElement(){
return this.element;
}
where element is an instance variable declared by E element. However when I try to return it in my gets method like this
public E get(int index){
Node current;
if(index < 0 || index >= size)
throw new IndexOutOfBoundsException();
if(index == 0)
return head.getElement();
else{
current = head;
for(int i = 0; i< index; i++){
current = current.getSuccessor();
}
return current.getElement();
}
}
I get the error cannot convert from object to type E. I can hack around it and type cast it to an E but I feel like there is some underlying thing about generics that I am missing. If you’ve guess that this is for homework you are correct and thank you in advance.
You probably want
Nodeto be generic too, so you’d have(I’ve simplified your code a little at the same time. In particular, it’s a good idea to declare variables at the point at which you actually need them.)
Node<E>would look like this: