Java高级(6)-泛型

泛型

传统方法的问题:

  • 不能对加入到集合ArrayList中的数据类型进行约束(不安全)
  • 遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响

泛型的应用:

  • ArrayList list = new ArrayList();
  • 表示存放到list集合中的元素是Dog类
  • 放入除Dog类的其他类型编译器直接会报错【编译时,检查添加元素的类型,提高了安全性】
  • 在遍历的时候也不需要向下转型【减少了类型转换的次数,提高效率】
  • 不再提示编译警告

介绍

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

泛型语法

泛型的声明

interface 接口{}

class 类<K,V>{}

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

泛型的实例化

要在类名后面指定类型参数的值(类型,只能是引用类型),如:

  • List strList = new ArrayList();
  • Iterator iterator = customers.iterator()

泛型使用的注意事项

//1.T,E等只能是引用类型
List<Integer> list = new ArrayList<Integer>();//ok
List<int> list2 = new ArrayList<int>();//不可以

//2.在指定泛型具体类型后,可以传入该类型或其子类类型
Pig<A> aPig = new Pig<A>(new A());//ok
Pig<A> aPig = new Pig<A>(new B());//ok
class A{};
class B extends A{}
class Pig<E>{
    E e;
    Public Pig(E e){
        this.e = e;
    }
}

//3.泛型使用形式
List<Integer> list = new ArrayList<Integer>();//ok
List<Integer> list = new ArrayList<>();//ok

//4.List list3 = new ArrayList();默认给它的泛型是【<E> E就是Object】

自定义泛型

泛型类

  • 基本语法
    • class 类名<T,R…>{ 成员 }//可以有多个泛型
  • 注意细节
    • 普通成员可以使用泛型(属性、方法)
    • 使用泛型的数组,不能初始化
    • 静态方法中不能使用类的泛型
    • 泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)
    • 如果在创建对象时,没有指定类型,默认为Object
public class CustomGeneric_ {
    public static void main(String[] args) {

        //T=Double, R=String, M=Integer
        Tiger<Double,String,Integer> g = new Tiger<>("john");
        g.setT(10.9); //OK
        //g.setT("yy"); //错误,类型不对
        System.out.println(g);
        Tiger g2 = new Tiger("john~~");//OK T=Object R=Object M=Object
        g2.setT("yy"); //OK ,因为 T=Object "yy"=String 是Object子类
        System.out.println("g2=" + g2);

    }
}

//老韩解读
//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) +
                '}';
    }
}

泛型接口

  • 基本语法
    • interface 接口名<T,R…>{}
  • 注意细节
    • 接口中,静态成员也不能使用泛型(这个和泛型类规定一样)
    • 泛型接口的类型,在继承接口或者实现接口时确定
    • 没有指定类型,默认为Object
/**
 *  泛型接口使用的说明
 *  1. 接口中,静态成员也不能使用泛型
 *  2. 泛型接口的类型, 在继承接口或者实现接口时确定
 *  3. 没有指定类型,默认为Object
 */

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

}
//当我们去实现IA接口时,因为IA在继承IUsu 接口时,指定了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;
    }
}

泛型方法

  • 基本语法
    • 修饰符 <T,R…>返回类型 方法名(参数列表){}
  • 注意细节
    • 泛型方法中,可以定义在普通类中,也可以定义在泛型类中
    • 当泛型方法被调用时,类型会确定
    • public void eat(E e){},修饰符后没有<T,R…> eat方法不是泛型方法,而是使用了泛型
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
    }

}

泛型继承和通配符

  • 泛型不具备继承性
    • List list = new ArrayList();不被允许
  • <?> 支持任意泛型类型
  • <? extends A> 支持A类以及A类的子类,规定了泛型的上限
  • <? super A> 支持A类以及A类的父类,不限于直接父类,规定了泛型的下限

JUnit

  • 一个类有很多功能代码需要测试,为了测试,就需要写入到main方法中
  • 如果有多个功能代码测试,就需要来回注销,切换很麻烦
  • 如果可以直接运行一个方法,就方便很多,并且可以给出相关信息,就好了

介绍

  • JUnit是一个Java语言的单元测试框架
  • 多数Java的开发环境都已经集成了Junit作为单元测试的工具
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 {
}
public class JUnit_ {
    public static void main(String[] args) {
        //传统方式
        //new JUnit_().m1();
        //new JUnit_().m2();

    }


    @Test
    public void m1() {
        System.out.println("m1方法被调用");
    }

    @Test
    public void m2() {
        System.out.println("m2方法被调用");
    }

    @Test
    public void m3() {
        System.out.println("m3方法被调用");
    }
}
public class Generic01 {
    public static void main(String[] args) {
        HashMap<String, Student> stringStudentHashMap = new HashMap<String, Student>();
        Student smith = new Student("smith", 18);
        Student mary = new Student("mary", 17);
        Student jack = new Student("jack", 19);
        stringStudentHashMap.put("smith",smith);
        stringStudentHashMap.put("mary",mary);
        stringStudentHashMap.put("jack",jack);
        Set<String> names = stringStudentHashMap.keySet();
        for(String name : names){
            System.out.println(name + "-" + stringStudentHashMap.get(name));
        }
        Set<Map.Entry<String,Student>> entrySet = stringStudentHashMap.entrySet();
        Iterator<Map.Entry<String, Student>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Student> entry = iterator.next();
            System.out.println(entry.getKey() + "-" + entry.getValue());
        }
    }
}
class Student{
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Generic02 {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("smith",4567.6,new MyDate(1997,4,3)));
        employees.add(new Employee("john",8567.6,new MyDate(1996,10,23)));
        employees.add(new Employee("jack",6567.6,new MyDate(1992,1,8)));
        employees.sort(new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                if(!(o1 instanceof Employee && o2 instanceof Employee)){
                    System.out.println("类型不正确");
                    return 0;
                }
                if(o1.getName().compareTo(o2.getName()) == 0){
                    return MyDate.sortDate(o1.getBirthday(),o2.getBirthday());
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Employee employee : employees) {
            System.out.println(employee);
        }

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

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

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}
class MyDate{
    private int year;
    private int month;
    private int date;

    public MyDate(int year, int month, int date) {
        this.year = year;
        this.month = month;
        this.date = date;
    }

    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 getDate() {
        return date;
    }

    public void setDate(int date) {
        this.date = date;
    }

    public static int sortDate(MyDate date1,MyDate date2){
        if(date1 == null || date2 == null){
            return 0;
        }
        if(date1.year != date2.year){
            return date1.year - date2.year;
        }else if(date1.month != date2.month){
            return date1.month - date2.month;
        }else{
            return date1.date - date2.date;
        }
    }

    @Override
    public String toString() {
        return year + "年" + month +
                "月" + date + "日";
    }
}
import org.junit.jupiter.api.Test;

import java.util.*;

public class Homework01 {
    public static void main(String[] args) {
        DAO<User> userDAO = new DAO<>();
        User smith = new User(1001, 18, "Smith");
        User mary = new User(1002, 33, "Mary");
        User jack = new User(1003, 19, "jack");
        User john = new User(1004, 28, "john");
        userDAO.save(smith.getName(),smith);
        userDAO.save(mary.getName(),mary);
        userDAO.save(jack.getName(),jack);
        System.out.println(userDAO);
        System.out.println(userDAO.get("Smith"));
        System.out.println(userDAO.get("jack"));
        userDAO.update("Mary",john);
        System.out.println(userDAO);
        System.out.println(userDAO.list());
        userDAO.delete("Mary");
        System.out.println(userDAO);
        userDAO.delete("jack");
        System.out.println(userDAO);
    }
}
class DAO<T>{
    private Map<String,T> map = new HashMap<>();
    @Test
    public void save(String id,T entity){
        map.put(id,entity);
    }
    @Test
    public T get(String id){
        return map.get(id);
    }
    @Test
    public void update(String id,T entity){
        map.replace(id,entity);
    }
    @Test
    public List<T> list(){
        Collection<T> values = map.values();
        List<T> list = new ArrayList<>();
        for(T value : values){
            list.add(value);
        }
        return list;
    }
    @Test
    public void delete(String id){
        map.remove(id);
    }

    @Override
    public String toString() {
        return "DAO{" +
                "map=" + map +
                '}';
    }
}
class User{
    private int id;
    private int age;
    private String name;

    public String getName() {
        return name;
    }

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

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值