Java泛型时JDK1.5中引入的一个新特性,其本质化是参数化类型,把类型作为参数传递
常见形式有泛型类 \ 泛型接口 \ 泛型方法
语法 : <T,...> T称为类型占位符,表示一种引用类型
2 防止类型转换异常, 提高代码安全性
泛型类
/**
* 泛型类
* 语法:类名<T>
* T是类型占位符,表示一种应用类型,如果写多个,用逗号隔开
*/
public class MyGeneric<T> {
//使用泛型T
//创建变量
T t;
//作为方法的参数
public void show(T t){
//不能用泛型直接new对象
System.out.println(t);
}
//使用泛型作为方法返回值
public T getT(){
return t;
}
}
public class TestGeneric {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:1.泛型只能是引用类型 2.不同的泛型类型对象之间不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "hello";
myGeneric.show("大家好!加油!");
String string = myGeneric.getT();
MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
myGeneric2.t = 100;
myGeneric2.show(200);
Integer integer =myGeneric2.getT();
}
}
泛型接口
/**
* 泛型接口
* 语法:接口名<T>
* 注意:不能使用泛型创建静态常量
*/
public interface MyInterface<T> {
String name = "张三";
T sever(T t);
}
使用方法一
继承的时候直接确定类型
public class MyInterfaceImpl implements MyInterface<String>{
使用方法二
继承的时候不确定类型
public class MyInterfaceImp2<T> implements MyInterface<T>{
泛型方法
/**
* 泛型方法
* 语法: <T> 返回值类型
*/
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法: "+t);
return t;
}
}
public class TestGeneric {
public static void main(String[] args) {
//泛型方法调用
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("中国");//这里的泛型根据所放入的值来改变
myGenericMethod.show(1000);//这里的泛型根据所放入的值来改变
myGenericMethod.show(314);//这里的泛型根据所放入的值来改变
}
}
泛型集合
概念: 参数化类型、类型安全的集合,强制集合元素的类型必须一致
特点:
-
编译时即可检查,而非运行时抛出异常
-
访问时,不必类型转换(拆箱)
-
不同泛型之间引用不能相互赋值,泛型不存在多态
public class Demo1 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
//指定了泛型 此时此刻就不能添加除字符串以外的类型
arrayList.add("xxx");
arrayList.add("yyy");
for (String s : arrayList) {
System.out.println(s);
}
ArrayList<Student> arrayList2 = new ArrayList<>();
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",18);
Student s3 = new Student("王二",22);
arrayList2.add(s1);
arrayList2.add(s2);
arrayList2.add(s3);
Iterator<Student> it = arrayList2.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.toString());
}
}
}
附:Student类
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}