泛型的简单理解
在不使用泛型时的代码。
public class MyLinkedList {
Node head = null;
int size;
class Node {
int data;
Node next = null;
public Node() {}
public Node(int data) {
this.data = data;
}
}
public void add (int element) {
if(head == null) {
Node node = new Node(element);
head = node;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(element);
}
}
public class Test {
public static void main(String[] args) {
MylinkedList a = new MylinkedList;
a.add(10);
}
}
在不使用泛型的时候,我们这个链表里只能存放int类型的数据,如果想存放String类型的数据时,我们只能通过重新修改MyLinkedList中的代码,这就造成了代码的重复。在java中,Sun公司为我们提供了一种方法可以不用这么麻烦,他就是泛型。
泛型
泛型就是把类型明确的工作推迟创建对象或者调用方法的方式。这个方式又称为参数化类型。
泛型的是使用方法分为三种,泛型类、泛型方法、泛型接口
泛型类
public class 类名< T > //< T >钻石表达式
在上面的代码中我们就可以这么来写
public class MyLinkedList<T> {
Node head = null;
int size;
class Node {
T data;
Node next = null;
public Node() {}
public Node(T data) {
this.data = data;
}
}
public void add (T element) {
if(head == null) {
Node node = new Node(element);
head = node;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(element);
}
}
在测试样例中
public class Test {
public static void main(String[] args) {
MylinkedList<int> a = new MylinkedList<>;
MylinkedList<String> b = new MylinkedList<>;
a.add(10);
b.add("aaa");
}
}
有了泛型,我们就不再需要麻烦的写重复代码。而是在创建对象的时候加入这个的类型就可以了。
泛型方法
public<泛型类型> 返回类型 方法名(泛型类型)
public class Test {
public <T> void show(T t) {
System.out.println(t);
}
}
泛型接口
public interface 接口名<泛型类型1>
泛型可以将问题提前暴露,优化了程序的设计。泛型在编译的时候会被你指定的类型所替换,当你提供给的类型和你指定的类型不一致的时候,他会在编译时就报错。