泛型
在JDK5之后,引入了泛型的概念:泛型是用来限制集合储存的数据类型的。
语法:
集合<数据类型> 变量 = new 集合<数据类型>()
注意:
-
数据类型不能是基本数据类型(集合本身储存的就是引用);
//ArrayList<int> al = new ArrayList<int>();//会报错 ArrayList<Integer> aList = new ArrayList<Integer>();//正确写法
-
在JDK8之后,引入了自动类型推断,后面<>中的数据类型可以省略不写;
集合<数据类型> 变量 = new 集合<>()
ArrayList<Integer> al = new ArrayList<>();
使用泛型的优缺点
-
在之前不使用泛型的案例中,遍历的元素是Object类型的,需要进行强制转换。
-
当使用泛型之后,在遍历的时候可以直接得到泛型数据类型,不再需要进行强制类型转换;但是也有缺点,使用泛型之后只能存储泛型限制的数据类型的数据,缺乏元素多样性,但是在业务开发中,数据类型都是比较统一的。
package com.dh.list;
import java.util.ArrayList;
public class ArrayList01 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// list.add(1);//会报错,只能存储String类型的数据
list.add("hello");
list.add("world");
//遍历可以直接得到String类型的数据,而不是Object然后强制转换
for (String s : list) {
System.out.println(s);
}
}
}
自定义泛型
泛型不仅仅应用于集合,在方法、类、接口中都可以使用泛型,并且还支持自定义的泛型。
泛型的位置可以是参数、返回值。
例:
package com.dh.list;
//自定义一个泛型
public class Student<abcdef> {
//书写一个参数为泛型的方法
public void show(abcdef arg){
System.out.println(arg);
}
//返回值为泛型数据
public abcdef print(){
return null;
}
public static void main(String[] args) {
//实例化对象,并指定泛型的具体数据类型
Student<String> student = new Student<>();
student.show("aaa");//此时参数就是String类型的
// student.show(111);//其它数据类型会报错
String print = student.print();//返回值为String类型
//指定其它的数据类型
Student<Integer> student1 = new Student<>();
student1.show(111);//参数就为Integer类型
Integer print1 = student1.print();//返回值为Integer类型
}
}