Java泛型

泛型是个啥

所谓泛型,“泛”即宽泛,也就是宽泛的类型,专业一点也叫作“参数化类型”。当使用泛型的时候,意味着我们的代码对类型没有严格要求,可以是Integer,可以是String,也可以是任意其他类型,通常用个T表示。

泛型的目的在于:我们能够写出适用于任何类型的模板代码。举个例子,JDK中的ArrayList类,如果按照如下方式编写:

1
2
3
4
5
6
7
8
public class ArrayList {
//用Object数组存储
private Object[] array;
private int size;
public void add(Object e) {...}
public void remove(int index) {...}
public Object get(int index) {...}
}

如果用上述ArrayList存储String类型,会有这么几个缺点: (1)需要强制转换类型;(2)不方便,容易出错。例如,代码可能要这样写:

1
2
3
4
ArrayList list = new ArrayList();
list.add("Hello");
// 获取到Object,必须强制转型为String:
String first = (String) list.get(0);

但是如果我们用上泛型,就能构建了一个能用于任何类型的模板:

1
2
3
4
5
6
7
public class ArrayList<T> {
private T[] array;
private int size;
public void add(T e) {...}
public void remove(int index) {...}
public T get(int index) {...}
}

现在我们可以轻松构建存储任意类型的ArrayList,使用时也不需要进行强制类型转换:

1
2
ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<String> strList = new ArrayList<String>();

泛型怎么用

前面我们介绍了什么是泛型,以及泛型有什么用,那么泛型有哪些用法呢?

Java中泛型有3种使用方式:泛型类、泛型接口、泛型方法。

泛型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class 类名称 <泛型标识:可以随便写任意标识号,标识指定的泛型的类型>{
private 泛型标识 /*(成员变量类型)*/ var;
.....

}
}
//就是把原来的具体类型都换成泛型标识T
class Example<T>{
private T val;

public Example(T val){
this.val = val;
}

public T getVal(){
return val;
}
}

泛型接口

和泛型类的用法基本一样。

1
2
3
4
//定义一个泛型接口
public interface Generator<T> {
public T next();
}

泛型方法

泛型方法也比较简单:普通方法的参数、返回值都是具体类型,如果把它们都改成泛型标识,就得到了一个泛型方法。

下面举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class DataHolder<T>{
T item;

public void setData(T t) {
this.item=t;
}

public T getData() {
return this.item;
}

/**
* 泛型方法
* @param e
*/
public <E> void PrinterInfo(E e) {
System.out.println(e);
}
}

需要注意的是:泛型方法既可以存在于泛型类中,也可以存在于非泛型类中。泛型方法和泛型类的区别在于:泛型方法是在调用该方法时才指定具体类型,而泛型类是在new一个实例的时候指定具体类型。

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2021-2022 Yin Peng
  • 引擎: Hexo   |  主题:修改自 Ayer
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信