Reputation: 503
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.
Upvotes: 1
Views: 135
Reputation: 1500873
You probably want Node
to be generic too, so you'd have
public E get(int index){
if(index < 0 || index >= size)
throw new IndexOutOfBoundsException();
Node<E> current = head;
for(int i = 0; i < index; i++) {
current = current.getSuccessor();
}
return current.getElement();
}
(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:
class Node<E> {
private final E element;
private Node<E> successor;
public Node(E element) {
this.element = element;
}
// etc
}
Upvotes: 9
Reputation: 111279
Assuming the Node class in generic, like it should be, your current
variable should be declared like this:
Node<E> current;
The same goes for head
and any other Nodes you may have.
Upvotes: 3