1、泛型的理解和好处
package com.francis.generic;
import java.util.ArrayList;
/**
* @author Francis
* @create 2021-10-23 16:59
*/
@SuppressWarnings({"all"})
public class Generic01 {
public static void main(String[] args) {
/*
请编写程序,在 ArrayList 中,添加 3 个 Dog 对象
Dog 对象含有 name 和 age, 并输出 name 和 age (要求使用 getXxx())
*/
//使用传统的方法来解决
ArrayList arrayList = new ArrayList();
arrayList.add(new Dog("旺财", 10));
arrayList.add(new Dog("发财", 1));
arrayList.add(new Dog("小黄", 5));
//假如我们的程序员,不小心,添加了一只猫
arrayList.add(new Cat("招财猫", 8));
//遍历
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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Cat { //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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
1.1、使用传统方法的问题分析
(1)不能对加入到ArrayList的数据类型进行约束。会导致例如上例中存在的类型转换异常等隐患
(2)遍历的时候,需要进行类型转换,如果集合的数据量较大,会影响程序的效率
1.2、泛型快速体验-用泛型来解决前面的问题
package com.francis.generic;
import java.util.ArrayList;
/**
* @author Francis
* @create 2021-10-23 17:10
*/
public class Generic02 {
public static void main(String[] args) {
/*
1.请编写程序,在 ArrayList 中,添加 3 个 Dog 对象
2.Dog 对象含有 name 和 age, 并输出 name 和 age (要求使用 getXxx())
*/
//使用传统的方法来解决===> 使用泛型
//1. 当我们 ArrayList<Dog> 表示存放到 ArrayList 集合中的元素是 Dog 类型 (细节后面说...)
//2. 如果编译器发现添加的类型,不满足要求,就会报错
//3. 在遍历的时候,可以直接取出 Dog 类型而不是 Object
//4. public class ArrayList<E> {} E 称为泛型,那么 Dog->E
ArrayList<Dog1> arrayList = new ArrayList<Dog1>();
arrayList.add(new Dog1("旺财", 10));
arrayList.add(new Dog1("发财", 1));
arrayList.add(new Dog1("小黄", 5));
//假如我们的程序员,不小心,添加了一只猫,此时相当于对元素类型做了规范,编译不通过
//arrayList.add(new Cat("招财猫", 8));
System.out.println("===使用泛型====");
for (Dog1 dog : arrayList) {
System.out.println(dog.getName() + "-" + dog.getAge());
}
}
}
class Dog1 {
private String name;
private int age;
public Dog1(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;
}
}
class Cat1 { //Cat 类
private String name;
private int age;
public Cat1(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;
}
}
1.3、泛型的理解和好处
(1)编译时,检查添加元素的类型,提高了安全性
(2)减少了类型转换的次数,提高了效率
2、泛型介绍
(1)泛型又称参数化类型,是JDK5.0出现的新特性,解决数据类型的安全性问题
(2)在类声明或实例化时只要指定好具体需要的类型即可
(3)Java泛型可以保证,如果程序在编译时没有发出警告,运行时就不会发生ClassCastException,同时,代码更加简介、健壮
(4)泛型的作用:可以在类声明时通过一个表示表示类中某个属性的类型或者是某个方法的返回值类型、或者是参数类型
package com.francis.generic;
/**
* @author Francis
* @create 2021-10-23 17:30
*/
public class Generic03 {
public static void main(String[] args) {
//注意,特别强调: E 具体的数据类型在定义 Person 对象的时候指定,即在编译期间,就确定 E 是什么类型
Person<String> person = new Person<String>("你好,北京!");
person.show(); //String
/*
你可以这样理解,上面的 Person 类
class Person {
String s ;//E 表示 s 的数据类型, 该数据类型在定义 Person 对象的时候指定,即在编译期间,就确定 E
是什么类型
public Person(String s) {//E 也可以是参数类型
this.s = s;
}
public String f() {//返回类型使用 E
return s;
}
}
*/
Person<Integer> person2 = new Person<Integer>(100);
person2.show();//Integer
/*
class Person {
Integer s ;//E 表示 s 的数据类型, 该数据类型在定义 Person 对象的时候指定,即在编译期间,就确定 E
是什么类型
public Person(Integer s) {//E 也可以是参数类型
this.s = s;
}
public Integer f() {//返回类型使用 E
return s;
}
}
*/
}
}
//泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,
// 或者是某个方法的返回值的类型,或者是参数类型
class Person<E> {
E s;//E 表示 s 的数据类型, 该数据类型在定义 Person 对象的时候指定,即在编译期间,就确定 E 是什么类型
public Person(E s) {//E 也可以是参数类型
this.s = s;
}
public E f() {//返回类型使用 E
return s;
}
public void show() {
System.out.println(s.getClass());//显示 s 的运行类型
}
}
3、泛型的语法
3.1、泛型的声明
接口:
interface 接口名<T>{}
类:
class 类名<E,F,G>{}
比如List和ArrayList的声明
其中的T、E、F、G不代表值,而是代表类型,任何字母都可以
3.2、泛型的实例化
要在类名的后面指定类型参数的值。
比如List list = new ArrayList ();
3.3、泛型使用的注意事项和细节
(1)interface List{},public class HashSet{}等等中的T,E只能是引用类型,例如List list2 = new ArrayList()编译不通过
(2)在实例化时指定具体的泛型类型后,可以传入该类型或者其子类类型
(3)如果带有泛型的接口或类在实例化时不指定泛型类型,则默认泛型为Object
package com.francis.generic;
import java.util.ArrayList;
import java.util.List;
/**
* @author Francis
* @create 2021-10-23 18:49
*/
@SuppressWarnings({"all"})
public class GenericDetail {
public static void main(String[] args) {
//1.给泛型指向数据类型是,要求是引用类型,不能是基本数据类型
List<Integer> list = new ArrayList<Integer>(); //OK
//List<int> list2 = new ArrayList<int>();//错误
//2. 说明
//因为 E 指定了 A 类型, 构造器传入了 new A()
//在给泛型指定具体类型后,可以传入该类型或者其子类类型
Pig<A> aPig = new Pig<A>(new A());
aPig.f();
Pig<A> aPig2 = new Pig<A>(new B());
aPig2.f();
//3. 泛型的使用形式
ArrayList<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
//在实际开发中,我们往往简写
//编译器会进行类型推断, 推荐使用下面写法
ArrayList<Integer> list3 = new ArrayList<>();
List<Integer> list4 = new ArrayList<>();
ArrayList<Pig> pigs = new ArrayList<>();
//4. 如果是这样写 泛型默认是 Object
ArrayList arrayList = new ArrayList();//等价 ArrayList<Object> arrayList = new ArrayList<Object>();
/*
public boolean add(Object e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
*/
Tiger tiger = new Tiger();
/*
class Tiger {//类
Object e;
public Tiger() {}
public Tiger(Object e) {
this.e = e;
}
}
*/
}
}
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()); //运行类型
}
}
3.4、泛型练习,结合比较器
package com.francis.generic.exercise;
import java.util.ArrayList;
import java.util.Comparator;
/**
* @author Francis
* @create 2021-10-23 19:21
*/
@SuppressWarnings({"all"})
public class GenericExercise02 {
/**
* 定义 Employee 类
* 1) 该类包含:private 成员变量 name,sal,birthday,其中 birthday 为 MyDate 类的对象;
* 2) 为每一个属性定义 getter, setter 方法;
* 3) 重写 toString 方法输出 name, sal, birthday
* 4) MyDate 类包含: private 成员变量 month,day,year;并为每一个属性定义 getter, setter 方法;
* 5) 创建该类的 3 个对象,并把这些对象放入 ArrayList 集合中(ArrayList 需使用泛型来定义),对集合中的元素进
* 行排序,并遍历输出:
* <p>
* 排序方式: 调用 ArrayList 的 sort 方法 , * 传入 Comparator 对象[使用泛型],先按照 name 排序,如果 name 相同,则按生日日期的先后排序。【即:定制排序】
*/
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee("tom", 20000, new MyDate(1980, 12, 11)));
employees.add(new Employee("jack", 12000, new MyDate(2001, 12, 12)));
employees.add(new Employee("tom", 50000, new MyDate(1980, 12, 10)));
System.out.println("employees=" + employees);
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee emp1, Employee emp2) {
//先按照 name 排序,如果 name 相同,则按生日日期的先后排序。【即:定制排序】
//先对传入的参数进行验证
if (!(emp1 instanceof Employee && emp2 instanceof Employee)) {
System.out.println("类型不正确..");
return 0;
}
//比较 name
int i = emp1.getName().compareTo(emp2.getName());
if (i != 0) {
return i;
}
//下面是对 birthday 的比较,因此,我们最好把这个比较,放在 MyDate 类完成
//封装后,将来可维护性和复用性,就大大增强.
return emp1.getBirthday().compareTo(emp2.getBirthday());
}
});
System.out.println("==对雇员进行排序==");
System.out.println(employees);
}
}
package com.francis.generic.exercise;
/**
* @author Francis
* @create 2021-10-23 19:23
*/
public class Employee {
private String name;
private double sal;
private MyDate birthday;
public Employee(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
@Override
public String toString() {
return "\nEmployee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
}
package com.francis.generic.exercise;
/**
* @author Francis
* @create 2021-10-23 19:22
*/
public class MyDate implements Comparable<MyDate> {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
@Override
public int compareTo(MyDate o) {
int yearMinus=this.year-o.getYear();
if (!(yearMinus==0)){
return yearMinus;
}
int monthMinus=this.month-o.getMonth();
if (!(monthMinus==0)){
return monthMinus;
}
int dayMinus=this.day-o.getDay();
return dayMinus;
}
}
4、自定义泛型
基本语法
class 类名<T,R...>{
//成员
}
注意细节:
(1)普通成员(属性、方法)可以使用泛型
(2)使用泛型的数组,不能初始化
(3)静态方法中不能使用类的泛型
(4)泛型类的类型,是在创建对象时确定的(因为只有在创建对象时,才会对类型参数进行指定)
(5)如果在创建对象时,没有指定类型参数,则默认为Object
4.1、自定义泛型类
package com.francis.generic.custom;
import java.util.Arrays;
/**
* @author Francis
* @create 2021-10-24 10:37
*/
public class CustomGeneric_ {
public static void main(String[] args) {
//T=Double, R=String, M=Integer
Tiger<Double,String,Integer> tiger = new Tiger<>("john");
tiger.setT(10.9); //OK
//g.setT("yy"); //错误,类型不对
System.out.println(tiger);
Tiger tiger2 = new Tiger("john~~");//OK T=Object R=Object M=Object
tiger2.setT("yy"); //OK ,因为 T=Object "yy"=String 是 Object 子类
System.out.println("tiger2=" + tiger2);
}
}
//1. Tiger 后面泛型,所以我们把 Tiger 就称为自定义泛型类
//2, T, R, M 泛型的标识符, 一般是单个大写字母
//3. 泛型标识符可以有多个. //4. 普通成员可以使用泛型 (属性、方法)
//5. 使用泛型的数组,不能初始化
//6. 静态方法中不能使用类的泛型
class Tiger<T, R, M> {
String name;
R r; //属性使用到泛型
M m;
T t;
//因为数组在 new 不能确定 T 的类型,就无法在内存开空间
T[] ts;
public Tiger(String name) {
this.name = name;
}
public Tiger(R r, M m, T t) {//构造器使用泛型
this.r = r;
this.m = m;
this.t = t;
}
public Tiger(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;
}
@Override
public String toString() {
return "Tiger{" +
"name='" + name + '\'' +
", r=" + r +
", m=" + m +
", t=" + t +
", ts=" + Arrays.toString(ts) +
'}';
}
}
4.2、自定义泛型接口
基本语法
interface 接口名<E,F...> {
}
注意细节
(1)接口中,静态成员也不能使用泛型(接口中成员属性默认就是静态的)
(2)泛型接口的类型参数,在继承接口或实现接口时确定(如果是接口,也可以继续定义类型参数)
(3)如果在继承接口或实现接口时没有指定类型,默认为Object
package com.francis.generic.custom;
/**
* @author Francis
* @create 2021-10-24 11:34
*/
public class CustomInterfaceGeneric {
public static void main(String[] args) {
}
}
/**
* 泛型接口使用的说明
* 1. 接口中,静态成员也不能使用泛型
* 2. 泛型接口的类型, 在继承接口或者实现接口时确定
* 3. 没有指定类型,默认为 Object
*/
//在继承接口 指定泛型接口的类型
interface IA extends IUsb<String, Double> {
}
interface IB<E,F> extends IUsb<E, F> {
}
//当我们去实现 IA 接口时,因为 IA 在继承 IUsb 接口时,指定了 U 为 String R 为 Double
//,在实现 IUsu 接口的方法时,使用 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) {
}
}
//实现接口时,直接指定泛型接口的类型
//给 U 指定 Integer 给 R 指定了 Float
//所以,当我们实现 IUsb 方法时,会使用 Integer 替换 U, 使用 Float 替换 R
class BB 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) {
}
}
//没有指定类型,默认为 Object
//建议直接写成 IUsb<Object,Object>
class CC implements IUsb { //等价 class CC 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) {
}
}
interface IUsb<U, R> {
int n = 10;
//U name; 不能这样使用
//普通方法中,可以使用接口泛型
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;
}
}
4.3、自定义泛型方法
基本语法:
修饰符 <T,R...> 返回类型 方法名(参数列表){
}
注意细节
(1)泛型方法,可以定义在普通类中,也可以定义在泛型类中
(2)当泛型方法被调用时,类型会确定
(3)public void eat(E e){},修饰符后没有T,R类型参数,eat方法不是泛型方法,而是使用了泛型
package com.francis.generic.custom;
import java.util.ArrayList;
/**
* @author Francis
* @create 2021-10-24 11:56
*/
@SuppressWarnings({"all"})
public class CustomMethodGeneric {
public static void main(String[] args) {
Car car = new Car();
car.fly("宝马", 100);//当调用方法时,传入参数,编译器,就会确定类型
System.out.println("=======");
car.fly(300, 100.1);//当调用方法时,传入参数,编译器,就会确定类型
//测试
//T->String, R-> ArrayList
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());//String
System.out.println(r.getClass());//Integer
}
}
class Fish<T, R> {//泛型类
public void run() {//普通方法
}
public<U,M> void eat(U u, M m) {//泛型方法
}
//说明
//1. 下面 hi 方法不是泛型方法
//2. 是 hi 方法使用了类声明的 泛型
public void hi(T t) {
}
//泛型方法,可以使用类声明的泛型,也可以使用自己声明泛型
public<K> void hello(R r, K k) {
System.out.println(r.getClass());//ArrayList
System.out.println(k.getClass());//Float
}
}
5、泛型的继承和通配符
5.1、泛型的继承和通配符说明
(1)泛型不具备继承性,例如
List list = new ArrayList()是不对的
(2)<?>支持任意泛型类型
(3)<? extends A>支持A类及A类的子类,规定了泛型的上限
(4)<? super A> 支持A类及A类的父类,规定了A类的上限
这里是起到规范的作用,注意,是在实例化时,给类型参数传值时使用,不能在定义泛型类时使用
package com.francis.generic;
import java.util.ArrayList;
import java.util.List;
/**
* @author Francis
* @create 2021-10-24 12:36
*/
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<AA> list3 = new ArrayList<>();
List<BB> list4 = new ArrayList<>();
List<CC> list5 = new ArrayList<>();
//如果是 List<?> c ,可以接受任意的泛型类型
printCollection1(list1);
printCollection1(list2);
printCollection1(list3);
printCollection1(list4);
printCollection1(list5);
//List<? extends AA> c: 表示 上限,可以接受 AA 或者 AA 子类
// printCollection2(list1);//×
// printCollection2(list2);//×
printCollection2(list3);//√
printCollection2(list4);//√
printCollection2(list5);//√
//List<? super AA> c: 支持 AA 类以及 AA 类的父类,不限于直接父类
printCollection3(list1);//√
//printCollection3(list2);//×
printCollection3(list3);//√
//printCollection3(list4);//×
//printCollection3(list5);//×
}
// ? extends AA 表示 上限,可以接受 AA 或者 AA 子类
public static void printCollection2(List<? extends AA> c) {
for (Object object : c) {
System.out.println(object);
}
}
//说明: List<?> 表示 任意的泛型类型都可以接受
public static void printCollection1(List<?> c) {
for (Object object : c) { // 通配符,取出时,就是 Object
System.out.println(object);
}
}
// ? super 子类类名 AA:支持 AA 类以及 AA 类的父类,不限于直接父类,
//规定了泛型的下限
public static void printCollection3(List<? super AA> c) {
for (Object object : c) {
System.out.println(object);
}
}
}
class AA {
}
class BB extends AA {
}
class CC extends BB {
}