目录
什么是泛型
泛型就相当于标签,它可以使代码更加通用、灵活和安全。在使用泛型时,程序员可以定义一种通用的类型或方法,并指定这些类型的实际参数,使其适用于不同的数据类型。
public class Demo01 {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("hello world");
al.add("luo");
al.add("jian");
al.add("bo");
for(Object o :al) {
System.out.println(o);
}
}
}
泛型总结
- 使用了泛型以后,可以确定集合中存放数据类型,在编译时期就可以检测出来
- 使用泛型可能会觉得麻烦,实际使用了泛型才会简单。
- 泛型的类型:都是引用数据类型,不能是基本数据类型。
- 简写:后面的类型可以省略不写
泛型类
public class GenericTest<E> {
}
类名后面的尖括号就是泛型 ,里面可以是 ABCD等等,一般类中泛型写成E
泛型方法
泛型的方法一定是要带有参数的才是有意义的 , 无参的都是无意义的
语法格式:
public <无意义的占位符> 返回值类型 方法的名字(参数列表) { }
无意义的占位符 可以是 T 可以是 E 或者 是 ? 等 都可以
public class GenericTest{
public static void main(String[] args) {
test(10);
test("hello");
test(true);
}
public static <T> void test(T types) {
System.out.println(types);
}
}
泛型类
语法格式:
class 类<无意义的占位符> {}
泛型类继承
class Animal<T> {
public void show(T t){}
}
class Dog<T> extends Animal<T> {
@Override
public void show(T t) {
System.out.println(t);
}
}
public class Test02 {
public static void main(String[] args) {
Dog<String> d = new Dog<>();
d.show("hello ");
}
}
泛型抽象类
abstract class Animal<T> {
abstract void show(T t);
}
class Dogs<T> extends Animal<T> {
@Override
void show(T t) {
System.out.println(t);
}
}
public class Demo01 {
public static void main(String[] args) {
Dogs<String> stringDogs = new Dogs<>();
stringDogs.show("hello world");
}
}
泛型的接口
语法格式:
interface 接口的名字<无意义的占位> {}
interface Person<T> {
void eating(T types);
}
class Student<T> implements Person<T> {
@Override
public void eating(T types) {
System.out.println(types);
}
}
public class Demo01 {
public static void main(String[] args) {
Student<String> stringStudent = new Student<>();
stringStudent.eating("hello world");
}
}