泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。
例子:
public class DLList<BleepBlorp> {
private IntNode sentinel;
private int size;
public class IntNode {
public IntNode prev;
public BleepBlorp item;
public IntNode next;
...
}
...
}
BleepBlorp可以为任意值。在调用class创建instance时:
DLList<Integer> d1 = new DLList<>(5);
d1.insertFront(10);
Interger作为数据类型的参数,将”替代“BleepBlorp。
也就是说,代码一在参数为Integer时等价于:
public class DLList {
private IntNode sentinel;
private int size;
public class IntNode {
public IntNode prev;
public int item;
public IntNode next;
...
}
...
}
特别的,在泛型为primitive type时,参数名称为:
Type | 参数名称 |
---|---|
int | Integer |
double | Double |
char | Character |
boolean | Boolean |
long | Long |
short | Short |
byte | Byte |
float | Float |
对于reference type,使用原本的类名即可。
参考:
https://www.runoob.com/java/java-generics.html
https://blog.csdn.net/s10461/article/details/53941091