泛型
泛型的理解和好处
需求
1.请编写程序,在ArrayList中,添加3个Dog对象
2.Dog对象含有name和age,并输出name和age(使用getXxx())
传统方法
Generic01:
@SuppressWarnings({"all"})
public class Generic01 {
public static void main(String[] args) {
// 用传统的方法
ArrayList arrayList = new ArrayList();
arrayList.add(new Dog("A",10));
arrayList.add(new Dog("B",1));
arrayList.add(new Dog("C",5));
// 加入不小心添加了一只猫
arrayList.add(new Cat("D",11)); // 会出现 ClassCastException
for (Object o : arrayList) {
// 向下转型 Object -> Dog
Dog dog = (Dog)o;
System.out.println(dog.getName() + "-" + dog.getAge());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Cat {
private String name;
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
使用传统方法的问题分析
1.不能对加入到集合 ArrayList中的数据类型进行约束(不安全)
2.遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响
使用泛型
Generic02:
@SuppressWarnings({"all"})
public class Generic02 {
public static void main(String[] args) {
// 用传统的方法 -> 使用泛型
// 1. 当 ArrayList<Dog> 表示存放到 ArrayList 集合中的元素是 Dog类型
// 2. 如果编译器发现添加的类型不满足要求,就会报错
// 3. 在遍历的时候,可以直接取出 Dog 类型,而不是 Object
ArrayList<Dog> arrayList = new ArrayList<Dog>();
arrayList.add(new Dog("A",10));
arrayList.add(new Dog("B",1));
arrayList.add(new Dog("C",5));
// 加入不小心添加了一只猫
// arrayList.add(new Cat("D",11)); // 报错
// 遍历
System.out.println("=== 使用泛型 ===");
for (Dog dog : arrayList) {
System.out.println(dog.getName() + "-" + dog.getAge());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Cat {
private String name;
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
泛型的好处
1.编译时,检查添加元素的类型,提高了安全性
2.减少了类型转换的次数,提高效率
3.不再提示编译警告
泛型介绍
泛型(即广泛类型) -> Integer,String,Dog
1.泛型又称参数化类型,是Jdk5.0出现的新特性,可以解决数据类型的安全性问题
2.在类声明或实例化时,只要指定好需要的具体类型即可
3.Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会发生异常,代码更加简洁、健壮
4.泛型的作用:可以在类声明时通过一个标识表示类中某个属性的类型, 或者是某个方法的返回值类型,或者是参数类型
Generic03:
public class Generic03 {
public static void main(String[] args) {
// 注意:E 具体的数据类型在定义Person对象时指定,
// 即在编译期间,就确定 E 是什么类型
Person<String> stringPerson = new Person<String>("hsp");
Person<Integer> integerPerson = new Person<>(100);
stringPerson.show(); // class java.lang.String
integerPerson.show(); // class java.lang.Integer
}
}
// 泛型的作用:可以在类声明时通过一个标识表示类中某个属性的类型,
// 或者是某个方法的返回值类型,或者是参数类型`
class Person<E> {
E s; // E 表示:s的数据类型,
public Person(E s) { // E 也可以是参数类型
this.s = s;
}
public E f() { // E 也可以是返回值类型
return s;
}
public void show() {
System.out.println(s.getClass()); // 显示s的运行类型
}
}
泛型的语法
泛型的声明
interface 接口 {} 和 class 类<K,V> {}
1.其中,T,K,V不代表值,而是表示类型
2.任意字母都可以,常用T表示,是Type的缩写
泛型的实例化
GenericExercise:
@SuppressWarnings({"all"})
public class GenericExercise {
public static void main(String[] args) {
HashSet<Student> studentHashSet = new HashSet<Student>();
studentHashSet.add(new Student("AA",18));
studentHashSet.add(new Student("BB",19));
studentHashSet.add(new Student("CC",20));
System.out.println("=== HashSet ===");
for (Student student : studentHashSet) {
System.out.println(student.name + "-" + student.age);
}
HashMap<String, Student> stringIntegerHashMap = new HashMap<String, Student>();
/*
public class HashMap<K,V>{}
*/
stringIntegerHashMap.put("AAA",new Student("AAA",18));
stringIntegerHashMap.put("BBB",new Student("BBB",19));
stringIntegerHashMap.put("CCC",new Student("CCC",21));
// 迭代器 EntrySet
System.out.println("=== EntrySet ===");
Set<Map.Entry<String, Student>> entries = stringIntegerHashMap.entrySet();
Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Student> entry = iterator.next();
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
}
class Student {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
泛型使用的注意事项和细节
1.interface List{} , public class HashSet{}…等等
说明:T,E 只能是引用类型
2.在指定泛型具体类型后,可以传入该类型或者其子类类型
3.泛型使用形式
4.如果这样写 泛型默认是Object
ArrayList list = new ArrayList();
等价于 ArrayList<Object> list = new ArrayList<>();
GenericDetail01:
@SuppressWarnings({"all"})
public class GenericDetail01 {
public static void main(String[] args) {
// 1.给泛型指定数据类型,要求是引用类型,不能是基本数据类型
ArrayList<Integer> list1 = new ArrayList<>(); // ok
// ArrayList<int> list2 = new ArrayList<>(); // error
// 2.在给泛型指定具体类型后,可以传入该类型或者其子类类型
Pig<A> aPig1 = new Pig<A>(new A());
aPig1.f();
Pig<A> aPig2 = new Pig<A>(new B());
aPig2.f();
// 3.泛型的使用形式
ArrayList<Integer> list3 = new ArrayList<>();
List<Integer> list4 = new ArrayList<>();
// 实际开发中,往往简写
// 编译器会进行类型推断
ArrayList<Integer> list5 = new ArrayList<>();
List<Integer> list6 = new ArrayList<>();
ArrayList<Pig> pigs = new ArrayList<>();
// 4.如果这样写 泛型默认是Object
ArrayList list = new ArrayList();
// 等价于 ArrayList<Object> list = new ArrayList<>();
// list.add(); // list.add(Object e)
// pigs.add(); // pigs.add(Pig e)
Tiger tiger = new Tiger();
}
}
class Tiger<E> {
E e;
public Tiger() {}
public Tiger(E e) {
this.e = e;
}
}
class A {}
class B extends A{}
class Pig<E> {
E e;
public Pig(E e) {
this.e = e;
}
public void f() {
System.out.println(e.getClass());
}
}
自定义泛型
自定义泛型类
CustomerGeneric_:
public class CustomerGeneric_ {
public static void main(String[] args) {
}
}
// 自定义泛型类:
// 1. Mouse<T,R,M> 称为自定义泛型
// 2. T,R,M 泛型的标识符,一般是单个大写字母
// 3. 泛型的标识符可以有多个
// 4. 普通成员可以使用泛型(属性、方法)
// 5. 使用泛型的数组,不能初始化
// 6. 静态方法中不能使用类的泛型
class Mouse<T,R,M> {
String name;
R r; // 属性使用泛型
M m;
T t;
// 数组在 new 不能确定 T 的类型,无法在内存开辟空间
// T[] ts = new T[8]; // error
public Mouse(String name, R r, M m, T t) { // 构造器使用泛型
this.name = name;
this.r = r;
this.m = m;
this.t = t;
}
// 静态是和类相关的,类加载时,对象还没有创建
// 所以如果静态方法和静态属性使用了泛型,JVM就无法完成初始化
// static R r2;
//
// public static void m1(M m) {
//
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 方法使用泛型
public R getR() {
return r; // 返回方法可以使用泛型
}
public void setR(R r) {
this.r = r;
}
public M getM() {
return m;
}
public void setM(M m) {
this.m = m;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
自定义泛型接口
CustomerInterfaceGeneric:
public class CustomerInterfaceGeneric {
public static void main(String[] args) {
}
}
// 自定义泛型接口:
// 1. 接口中,静态成员也不能使用泛型
// 2. 泛型接口的类型,在继承接口或者实现接口时确定
// 3. 没有指定类型,默认为Object
// 继承接口,指定泛型接口的类型
interface IA extends IUsb<String, Double> {
}
// 当实现IA接口时,IA在继承IUsb接口时,指定了 U 为 String, R 为 Double
// 在实现IUsb接口的方法时,使用 String替换 U ,Double替换 R
class AA implements IA {
@Override
public Double get(String s) {
return null;
}
@Override
public void hi(Double aDouble) {
}
@Override
public void run(Double r1, Double r2, String u1, String u2) {
}
}
// 没有指定类型,默认为Object
class IC implements IUsb { // 等价于 class IC implements IUsb<Object,Object>
@Override
public Object get(Object o) {
return null;
}
@Override
public void hi(Object o) {
}
@Override
public void run(Object r1, Object r2, Object u1, Object u2) {
}
}
// 实现接口时,直接指定泛型接口的类型
class IB implements IUsb<Integer,Float> {
@Override
public Float get(Integer integer) {
return null;
}
@Override
public void hi(Float aFloat) {
}
@Override
public void run(Float r1, Float r2, Integer u1, Integer u2) {
}
}
interface IUsb<U,R> {
// 接口中的属性,只能是 final 的,而且是 public static final 修饰符
int n = 10;
// U name; // error
// 普通方法中,可以使用接口泛型
R get(U u);
void hi(R r);
void run(R r1, R r2, U u1, U u2);
// 在jdk8中,可以在接口中,使用默认方法,也可以使用泛型
default R method(U u) {
return null;
}
}
自定义泛型方法
CustomerMethodGeneric:
public class CustomerMethodGeneric {
public static void main(String[] args) {
Car car = new Car();
// 调用方法时,传入参数,编译器就会确定类型
car.fly("宝马",100);
car.fly(12.3,'1');
Fish<String, ArrayList> fish = new Fish<>();
fish.hello(new ArrayList(),11.3f);
}
}
// 自定义泛型方法:
//
class Car {
public void run() {
}
// 泛型方法
// 1. <T,R> 就是泛型
// 2. 是提供给fly使用的
public<T,R> void fly(T t, R r) {
System.out.println(t.getClass());
System.out.println(r.getClass());
}
}
// 泛型类
class Fish<T,R> {
public void run() {
}
public<U,M> void eat(U u, M m) {
}
// hi方法不是泛型方法,而是使用了类声明的泛型
public void hi(T t) {
}
// 泛型方法可以使用:
// 1. 类声明的泛型
// 2. 自己声明的泛型
public<K> void hello(R r, K k) {
System.out.println(r.getClass()); // ArrayList
System.out.println(k.getClass()); // Float
}
}
泛型的继承和通配符
泛型的继承和通配符说明
GenericExtends:
public class GenericExtends {
public static void main(String[] args) {
Object o = new String("xx");
// 泛型没有继承性
// List<Object> list = new ArrayList<String>();
// 举例下面三个方法的使用
List<Object> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
List<AAA> list3 = new ArrayList<>();
List<BBB> list4 = new ArrayList<>();
List<CCC> list5 = new ArrayList<>();
// List<?> c 可以接收任意的泛型类型
printCollection1(list1);
printCollection1(list2);
printCollection1(list3);
printCollection1(list4);
printCollection1(list5);
// List<? extends AAA> c
printCollection2(list3);
printCollection2(list4);
printCollection2(list5);
// List<? super AAA> c
printCollection3(list1);
printCollection3(list3);
}
// List<?> 表示 任意的泛型类型都可以接收
public static void printCollection1(List<?> c) {
for (Object o : c) {
System.out.println(o);
}
}
// ? extends AAA 表示 上限,可以接收 AAA 或者 AAA 的子类
public static void printCollection2(List<? extends AAA> c) {
for (Object o : c) {
System.out.println(o);
}
}
// ? super 子类类名AAA 表示 下限,支持 AAA类以及 AAA类的父类,不限于直接父类
public static void printCollection3(List<? super AAA> c) {
for (Object o : c) {
System.out.println(o);
}
}
}
class AAA {
}
class BBB extends AAA {
}
class CCC extends BBB {
}