I’m looking at an example implementation of a linkedlist consisting of nodes. The set method goes to the input index and sets the value equal to the input value. Additionally, it returns the old value. When he retrieves the old value he always creates a new node object instead of an object of type E. Is that necessary or is that considered good practice? Also are there any efficiency considerations? Example code below
public E set(int idx, E newVal){
//looping code to get to the right node
//Assume variable finger is now a Node object that's at the right index
Node<E> temp = new Node<E>(finger);
finger.setValue(newVal);
return temp.getValue();
//Can I do the following instead?
E temp = finger.getValue();
finger.setValue(newVal);
return temp;
}
No, it’s perfectly acceptable to use the generic type parameter (
Ein this case). There’s nothing wrong with your second code sample.According to the Generics FAQ: