文档

Java™ 教程-Java Tutorials 中文版
删除泛型类型
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Type Erasure

删除泛型类型

在类型擦除过程中,Java 编译器将擦除所有类型形参,并在类型形参有界时将其替换为第一个边界,如果类型形参无界,则替换为 Object

考虑以下表示单链表中节点的泛型类:

public class Node<T> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

由于类型形参 T 是无界的,因此 Java 编译器将其替换为 Object

public class Node {

    private Object data;
    private Node next;

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Object getData() { return data; }
    // ...
}

在以下示例中,泛型 Node 类使用有界类型形参:

public class Node<T extends Comparable<T>> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

Java 编译器用第一个边界类 Comparable 替换有界类型形参 T

public class Node {

    private Comparable data;
    private Node next;

    public Node(Comparable data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Comparable getData() { return data; }
    // ...
}

Previous page: Type Erasure
Next page: Erasure of Generic Methods