java泛型是JDK1.5中引入的新特性,本质是参数化类型,类型安全的集合,强制集合元素的类型必须一致。提高方法的重用性。
1.泛型的分类
1.1 泛型类
在类名的后面加一对尖括号,加括号中包含一个字母,这个字母是占位符,占位符使用一个大写字母表示,创建对象时替换为实际的类型,如果有多个用逗号隔开,这样的类称为泛型类。
常用占位符:E(element)、T(Type)、V(Value)、K(Key)
格式:public class GenericDemo1 {}
使用:
- 1.创建实例变量,不能创建静态的 T n;
- 2.作为方法的参数
- 3.作为方法的返回值
public T print(T t) {
return t;
}
//在类名的后面加一对尖括号,加括号中包含一个字母,这个字母是占位符
//占位符使用一个大写字母表示,创建对象时替换为实际的类型
//如果有多个用逗号隔开<E,T>
//E(element) T(Type) V(Value) K(Key)
// 这样的类称为泛型类
public class GenericDemo1<T> {
//1.创建实例变量,不能创建静态的
T n;
//2.作为方法的参数
public T print(T t) {
//3.作为方法的返回值
return t;
}
}
class Test {
public static void main(String[] args) {
GenericDemo1<String> demo = new GenericDemo1<>();
demo.n = "123";
System.out.println(demo.print("asd"));
}
}
1.2 泛型接口
在接口名的后面加一对尖括号,尖括号包含占位符,这样的接口就称为泛型接口。
格式:public interface GenericDemo2{}
使用:作为参数、返回值 T print(T t);
//在接口名的后面加一对尖括号,尖括号包含占位符,这样的接口就称为泛型接口
public interface GenericDemo2<T> {
//1.作为参数、返回值
T print(T t);
}
//实现接口1
class Mouse implements GenericDemo2<String> {
@Override
public String print(String s) {
return s;
}
}
//实现接口2
class Upan<E> implements GenericDemo2<E>{
@Override
public E print(E e) {
return e;
}
}
class Test2 {
public static void main(String[] args) {
Mouse mouse = new Mouse();
//GenericDemo2<String> mouse2 = new Mouse()
System.out.println(mouse.print("123"));
Upan<String> upan = new Upan<>();
//GenericDemo2<String> upan2 = new Mouse()
System.out.println(upan.print("456"));
}
}
Click here to view the copyright notice of this site(点击此处查看本站版权声明)
必须 注册 为本站用户, 登录 后才可以发表评论!