Java泛型

泛型的理解和好处

使用传统方法的问题分析

  1. 不能对加入到集合ArrayList中的数据类型进行约束(不安全)
  2. 遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响
  3. 传统方法案例演示:

package com.xz.generic;

import java.util.ArrayList;

/**
 * @author 许正
 * @version 1.0
 */
public class Generic01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Dog("旺财", 8));
        arrayList.add(new Dog("大黄", 9));
        arrayList.add(new Dog("小白", 5));

        //假如不小心添加了一只猫类
//        arrayList.add(new Cat("小黑", 5));//向下转型时会出错

        //循环遍历
        for (Object o : arrayList) {
            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 {
    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;
    }
}

用泛型来解决前面的问题

package com.xz.generic.improve;

import java.util.ArrayList;

/**
 * @author 许正
 * @version 1.0
 */
public class Generic02 {
    public static void main(String[] args) {
        //1. 当我们ArrayList<Dog> 表示存放到ArrayList 集合中的元素是Dog类型 (细节之后面的博文谈及...)
        //2. 如果编译器发现添加的类型,不满足要求,就会报错
        //3. 在遍历的时候,可以直接取出Dog类型而不是Object
        ArrayList<Dog> dogs = new ArrayList<>();
        dogs.add(new Dog("旺财", 8));
        dogs.add(new Dog("大黄", 9));
        dogs.add(new Dog("小白", 5));
        //假如程序员不小心添加了一只猫类
//        dogs.add(new Cat("小黑", 5));//编译器会检测到并提示错误

        System.out.println("===使用泛型===");
        for (Dog dog : dogs) {
            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 {
    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. 编译时,检查添加元素的类型,提高了安全性
  2. 减少了类型转换的次数,提高效率[说明]
  • 不使用泛型
    Dog -加入-> Object -取出-> Dog //放入到ArrayList会先转成Object,在取出时,还需要转换成Dog
  • 使用泛型
    Dog -> Dog -> Dog /放入时,和取出时,不需要类型转换,提高效率
  1. 不再提示编译警告

泛型介绍

泛型=> Integer, String,Dog

  1. 泛型又称参数化类型,是Jdk5.0 出现的新特性解决数据类型的安全性问题
  2. 在类声明或实例化时只要指定好需要的具体的类型即可。
  3. Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生
    ClassCastException异常。同时,代码更加简洁、健壮
  4. 泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方
    法的返回值的类型,或者是参数类型。

演示:

package com.xz.generic;

/**
 * @author 许正
 * @version 1.0
 */
public class Generic03 {
    public static void main(String[] args) {
        //注意,特别强调: E具体的数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
        Person<String> person1 = new Person<>("许正");
        person1.printClass();
        Person<Integer> person2 = new Person<>(100);
        person2.printClass();
    }
}


//泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,
//或者是某个方法的返回值的类型,或者是参数类型
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 printClass() {//显示s的运行类型
        System.out.println(s.getClass());
    }
}

泛型的语法

泛型的声明

interface接口{}和class类<K,V>{}
//比如: List , ArrayList
说明:

  1. 其中,T,K,V不代表值,而是表示类型。
  2. 任意字母都可以。常用T表示,是Type的缩写

泛型的实例化:

要在类名后面指定类型参数的值(类型)。如:

  1. List strList = new ArrayList < String> ();
  2. Iterator iterator = customers.iterator();

练习:

package com.xz.generic;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author 许正
 * @version 1.0
 */
public class GenericExercise {
    public static void main(String[] args) {
        System.out.println("====HashSet====");
        HashSet<Student> students = new HashSet<Student>();
        students.add(new Student("小明", 18));
        students.add(new Student("帅豪", 23));
        students.add(new Student("猪皮", 21));

        for (Student student : students) {
            System.out.println(student.getName());
        }

        System.out.println("====HashMap====");
        HashMap<Integer, Student> map = new HashMap<>();
        map.put(1, new Student("小明", 18));
        map.put(2, new Student("帅豪", 23));
        map.put(3, new Student("猪皮", 21));
        map.put(4, new Student("正正", 21));

        Set<Map.Entry<Integer, Student>> entries = map.entrySet();
        for (Map.Entry<Integer, Student> entry : entries) {
            System.out.println(entry.getKey() + "-" + entry.getValue().getName());
        }
    }
}

class Student {
    private String name;
    private int age;

    public Student(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. interface List{} , public class HashSet{}…等等
    说明: T, E只能是引用类型
    看看下面语句是否正确?:
    List list = new ArrayList ();//OK
    List list2 = new ArrayList );//F,不可以是基本类型

  2. 在指定泛型具体类型后,可以传入该类型或者其子类类型

  3. 泛型使用形式
    List list1 = new ArrayList< Integer> );

//可以简写为下面的形式(推荐!)

List list2 = new ArrayList< > ();

  1. 如果我们这样写List list3 = new ArrayList();默认给它的泛型是[ E就是Object ]

练习

请添加图片描述

package com.xz.generic;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @author 许正
 * @version 1.0
 */
public class GenericExercise02 {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("jack", 10000, new Birthday(2002, 12, 8)));
        employees.add(new Employee("tom", 12000, new Birthday(2000, 3, 5)));
        employees.add(new Employee("jack", 8000, new Birthday(2002, 11, 20)));

        //遍历输出
        for (Employee employee : employees) {
            System.out.println(employee);
        }

        employees.sort(new Comparator<Employee>() {
            @Override
            public int compare(Employee emp1, Employee emp2) {
                //判断类型是否有误
                if (!(emp1 instanceof Employee && emp2 instanceof Employee)) {
                    System.out.println("类型不正确...");
                    return 0;
                }
                //判断名字是否相同
                int i = emp1.getName().compareTo(emp2.getName());
                if (i != 0) {
                    return i;
                }
                //判断生日,把比较生日的方法封装到Birthday类里
                return emp1.getBirthday().compareTo(emp2.getBirthday());

            }
        });

        //再次遍历
        System.out.println("排序后:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

class Employee {
    private String name;
    private double sal;
    private Birthday birthday;

    public Employee(String name, double sal, Birthday birthday) {
        this.name = name;
        this.sal = sal;
        this.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 Birthday getBirthday() {
        return birthday;
    }

    public void setBirthday(Birthday birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}

class Birthday implements Comparable<Birthday> {
    private int year;
    private int month;
    private int day;

    public Birthday(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 "Birthday{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }


    @Override
    public int compareTo(Birthday o) {
        //先判断年份
        int yearMinus = year - o.getYear();
        if (yearMinus != 0) {
            return yearMinus;
        }
        //判断月份
        int monthMinus = month - o.getMonth();
        if (monthMinus != 0) {
            return monthMinus;
        }
        //判断日
        int dayMinus = day - o.getDay();
        return dayMinus;
    }
}

自定义泛型

自定义泛型类(难点)

➢基本语法

class类名<T, R...> {//也可以是接口,  ...表示可以有多个泛型
	//成员
}

➢注意细节

  1. 普通成员可以使用泛型(属性、方法)
  2. 使用泛型的数组,不能初始化
  3. 静态方法中不能使用类的泛型
  4. 泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)
  5. 如果在创建对象时,没有指定类型,默认为Object
package com.xz.customgeneric;

/**
 * @author 许正
 * @version 1.0
 */
public class CustomGeneric {
    public static void main(String[] args) {

    }
}

//1. Tiger 后面泛型,所以我们把Tiger 就称为自定义泛型类
//2, T, R, M泛型的标识符,一般是单个大写字母
//3.泛型标识符可以有多个。
//4.普通成员可以使用泛型(属性、方法)
//5. 使用泛型的数组,不能初始化
//6. 静态方法中不能使用类的泛型
//7. 泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)
//8. 如果在创建对象时,没有指定类型,默认为Object
class Tiger<T, R, M> {
    String name;
    T t;//属性使用到泛型
    R r;
    M m;
    //因为数组在new不能确定T的类型,就无法在内存开空间
    T[] ts;

    //因为静态是和类相关的,在类加载时,对象还没有创建
    //所以,如果静态方法和静态属性使用了泛型,JVM就无法完成初始化
//    static R r2;
//    public static void m1(M m) {
//
//    }
    
    public Tiger(String name, T t, R r, M m) {//构造器使用到泛型
        this.name = name;
        this.t = t;
        this.r = r;
        this.m = m;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public T getT() {//返回类型使用到泛型
        return t;
    }

    public void setT(T t) {//方法使用到泛型
        this.t = t;
    }

    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;
    }
}

自定义泛型接口

➢基本语法

interface接口名<T, R...> {
}

➢注意细节

  1. 接口中,静态成员也不能使用泛型(这个和泛型类规定一样)
  2. 泛型接口的类型,在继承接口或者实现接口时确定
  3. 没有指定类型,默认为Object
package com.xz.customgeneric;

/**
 * @author 许正
 * @version 1.0
 */
public class CustomInterfaceGenetic {
    public static void main(String[] args) {

    }
}

/**
 * 泛型接口使用的说明
 * 1) 接口中,静态成员也不能使用泛型(这个和泛型类规定一样)
 * 2) 泛型接口的类型,在**继承接口**或者**实现接口**时确定
 * 3) 没有指定类型,默认为Object
 */

//在继承接口 指定泛型接口的类型
interface IA extends IUsb<String, Double> {

}

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;
    }
}

//当我们去实现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) {

    }
}

自定义泛型方法

➢基本语法

修饰符<T,R..>返回类型 方法名(参数列表) {
}

注意细节

  1. 泛型方法,可以定义在普通类中,也可以定义在泛型类中
  2. 当泛型方法被调用时,类型会确定
  3. public void eat(E e) {},修饰符后没有<T,R…> eat
    方法不是泛型方法,而是使用了泛型
package com.xz.customgeneric;

import java.util.ArrayList;

/**
 * @author 许正
 * @version 1.0
 * 泛型方法的使用
 */
public class CustomMethodGenetic {
    public static void main(String[] args) {
        Car car = new Car();
        car.fly("宝马", 400000);//当调用方法时,传入参数,编译器,就会确定类型
        car.fly(300, 100.1);

        System.out.println("=============");
        //测试
        //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() + " || " + r.getClass());
    }
}

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());
        System.out.println(k.getClass());
    }
}

泛型的继承和通配符

泛型的继承和通配符说明

  1. 泛型不具备继承性
List<Object> list = new ArrayList<String> 0; //错误
  1. <?> :支持任意泛型类型
  2. <? extends A>:支持A类以及A类的子类,规定了泛型的上限
  1. <? super A>:支持A类以及A类的父类,不限于直接父类,规定了泛型的下限
package com.xz.genericextends;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 许正
 * @version 1.0
 * 泛型的继承和通配符
 */
public class GenericExtends {
    public static void main(String[] args) {
        Object pork = new String("pork");

        //泛型没有继承性
//        ArrayList<Object> strings = new ArrayList<String>();//F

        //举例说明下面三个方法的使用
        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<>();

        printCollection1(list1);
        printCollection1(list2);
        printCollection1(list3);
        printCollection1(list4);
        printCollection1(list5);

        // ? extends AA 表示上限,可以接受AA或者AA子类
//        printCollection2(list1);//F
//        printCollection2(list2);//F
        printCollection2(list3);
        printCollection2(list4);
        printCollection2(list5);

        // ? super AA  表示下限,可以接受AA或者AA父类
        printCollection3(list1);
//        printCollection3(list2);//F
        printCollection3(list3);
//        printCollection3(list4);//F
//        printCollection3(list5);//F

    }

    //List<?> 表示 任意的泛型类型都可以接收
    public static void printCollection1(List<?> c) {
        for (Object o : c) {// 通配符,取出时就是 Object
            System.out.println(o);
        }
    }

    // ? extends AA 表示上限,可以接受AA或者AA子类
    public static void printCollection2(List<? extends AA> c) {
        for (Object o : c) {
            System.out.println(o);
        }
    }

    // ? super 子类类名AA:支持AA类以及AA类的父类,不限于直接父类,
    //规定了泛型的下限
    public static void printCollection3(List<? super AA> c) {
        for (Object o : c) {
            System.out.println(o);
        }
    }

}

class AA {
}

class BB extends AA {
}

class CC extends BB {
}

Exercise

请添加图片描述

package com.xz.homework;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @author 许正
 * @version 1.0
 */
public class Homework01 {
    public static void main(String[] args) {

    }


    @Test
    public void testList() {
        DAO<User> userDAO = new DAO<>();
        userDAO.save("001", new User(1, 18, "jack"));
        userDAO.save("002", new User(2, 21, "tom"));
        userDAO.save("003", new User(3, 19, "smith"));

        List<User> list = userDAO.list();
        System.out.println(list);

        userDAO.update("002", new User(2, 23, "帅豪"));
        userDAO.delete("001");
        System.out.println(userDAO.get("003"));

        list = userDAO.list();
        System.out.println(list);
    }

}

class DAO<T> {
    Map<String, T> map = new HashMap<>();

    public void save(String id, T entity) {
        map.put(id, entity);
    }

    public T get(String id) {
        return map.get(id);
    }

    public void update(String id, T entity) {
        map.put(id, entity);
    }

    public List<T> list() {
        ArrayList<T> ts = new ArrayList<>();
        Set<Map.Entry<String, T>> entries = map.entrySet();
        for (Map.Entry<String, T> entry : entries) {
            ts.add(entry.getValue());
        }
        return ts;
    }

    public void delete(String id) {
        map.remove(id);
    }
}
package com.xz.homework;

/**
 * @author 许正
 * @version 1.0
 */
public class User {
    private int id;
    private int age;
    private String name;

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员正正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值