java is it bad to declare a variable of type E (generics)
I'm looking at an example implementation of a linkedlist consisting of nodes. The set method goes to the input index a开发者_运维问答nd 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 (E
in this case). There's nothing wrong with your second code sample.
According to the Generics FAQ:
Can I use a type parameter like a type?
No, a type parameter is not a type in the regular sense (different from a regular type such as a non-generic class or interface).
Type parameters can be used for typing (like non-generic classes and interfaces)::
- as argument and return types of methods
- as type of a field or local reference variable
- as type argument of other parameterized types
- as target type in casts
- as explicit type argument of parameterized methods
Type parameters can NOT be used for the following purposes (different from non-generic classes and interfaces)::
- for creation of objects
- for creation of arrays
- in exception handling
- in static context
- in instanceof expressions
- as supertypes
- in a class literal
Assuming that setValue()
and getValue()
modify the same attribute, the first 3 lines of code will return newVal
(they don't make much sense)
temp
is a reference to finger
, so if you set a new value to an attribute in finger
, then it will change in temp
.
The last three lines don't have the same behavior, since they return the previous value.
That impl is quite odd. It probably was translated from a C++ impl
Node<E> temp = finger; // C++, copy constructor, default is shallow copy
finger.setValue(newVal);
return temp.getValue();
That would be very cheap for C++.
精彩评论