泛型
- 其本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- <E,…> E称为类型占位符,表示一种引用类型
- 好处:
- 提高代码的重用性
- 防止类型转换异常,提高代码的安全性
- 不能实例化
- 泛型只能使用引用类型
- 不同泛型类型对象之间不能相互赋值
泛型类
public class Demo10<T> {
//使用泛型
//创建变量
T t;
//作为方法的参数
public void show(T t){
System.out.println(t);
}
//使用泛型作为方法的返回值
public T getT(){
return t;
}
}
public class TestDemo10 {
public static void main(String[] args) {
//使用泛型类创建对象
Demo10<String> str = new Demo10<>();
str.t="hello";
str.show("world");
str.getT();
}
}
泛型接口
public interface MyInterface<T> {
String name = "zhangsan";
//不能使用泛型创建静态常量
T server(T s);
}
类中定义数据类型
public class MyInterfac implements MyInterface<String> {
//快捷键:ctrl+I
@Override
public String server(String t) {
System.out.println(t);
return t;
}
类中不定义数据类型
public class MyInterfac2<T> implements MyInterface<T> {
@Override
public T server(T s) {
System.out.println(s);
return s;
}
MyInterfac my = new MyInterfac();
my.server("su");
MyInterfac2<String> str2 = new MyInterfac2<>();
str2.server("li");
泛型方法: 类型不需要传递,是由我们传递的数据决定的
ublic class Method {
public <T> void show(T t){
System.out.println("泛型方法"+t);
}
public <T> T show2(T t){
System.out.println(t);
return t;
}
Method method = new Method();
method.show(3);
method.show2("su");
泛型集合
- 概念:参数化类型、类型安全的集合,强制集合类型的元素必须一致
- 特点
- 编译时即可检查,而非运行时抛出异常
- 访问时不必类型转换(拆箱)
- 不同泛型之间引用不能相互赋值,泛型不存在多态
public static void main(String[] args) {
ArrayList a = new ArrayList<>();
a.add("su");
a.add(1);
for (Object o : a) {
String s = (String)o;
System.out.println(s);//报错
}
ArrayList<Student> arry = new ArrayList<>();
Student s1 = new Student("su", 15);
Student s2 = new Student("wang", 20);
Student s3 = new Student("li", 5);
arry.add(s1);
arry.add(s2);
arry.add(s3);
Iterator<Student> iterator = arry.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}