Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of If a generic type variable is used as a field in a class, should it include the expression? without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have a generic type Node:
public class Node<T> { private T element; private Node<T> next; public T getElem() { return element; } public Node<T> getNext() { return next; } public void setElem(T newElem) { element = newElem; } public void setNext(Node<T> n) { next = n; } }
And I used it as a field in the class DynamicList:
public class DynamicList<T> implements MyList<T>{ private Node<T> head; }
I found that when I used
private Node head;
It won’t affect the list behaviors. So which one is right?
Answer
Seriously it will not effect the behavior, because the types are erased at runtime. But if you do not specifiy a generic type argument, there is no type check and this can lead you to programming mistakes. So the first one is the better solution. If you are using a compiler with the right configurations, it should tell you that you are using the Raw type when writing private Node head;
.
We are here to answer your question about If a generic type variable is used as a field in a class, should it include the expression? - If you find the proper solution, please don't forgot to share this with your team members.