简体   繁体   中英

If a generic type variable is used as a field in a class, should it include the <T> expression?

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?

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; .

The first is case is that the generic type check

And in your second case

private Node head;

That means here your are using Raw type which is equivalent to

private Node<Object> head;

Where Object is T now.

The Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

You should avoid using raw types. Codes using Raw types are unsafe code to runtime

Using Node<T> you ensure that DynamicList can no accept nodes with other data Type for Node.element . Other way, there is no restriction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM