java_泛型

一、看一个需求

在这里插入图片描述
这里是引用
在这里插入图片描述

二、泛型介绍

在这里插入图片描述

三、泛型的语法

在这里插入图片描述
在这里插入图片描述

@SuppressWarnings({"all"})
public class Generic02 {
    public static void main(String[] args) {
        HashSet<Student> students = new HashSet<>();
        students.add(new Student("jack", 18));
        students.add(new Student("tom", 28));
        students.add(new Student("mary", 19));
        //遍历
        for (Student student :students) {
            System.out.println(student);
        }
        //使用泛型方式给HashMap 放入3个学生对象
        HashMap<String, Student> hm = new HashMap<>();
        hm.put("milan", new Student("milan", 28));
        hm.put("smith", new Student("smith", 28));
        hm.put("hsp", new Student("hsp", 28));

        //迭代器 EntrySet
        Set<Map.Entry<String, Student>> entries = hm.entrySet();
        Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
        System.out.println("=========迭代器==============");
        while (iterator.hasNext()) {
            Map.Entry<String, Student> next =  iterator.next();
            System.out.println(next.getKey() + "-" + next.getValue());
        }


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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
引用数据类型默认都继承Object类所以此处默认用Object类在这里插入图片描述

四、泛型课堂类型

在这里插入图片描述

public class Generic02 {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("tom", 20000, new MyDate(2000,11,11)));
        employees.add(new Employee("jack", 12000, new MyDate(2001,12,12)));
        employees.add(new Employee("hsp", 50000, new MyDate(1980,10,10)));

        System.out.println("employees=" + employees);
        System.out.println("===对雇员进行排序===");
        //先按name,如果name相同,按出生日期排序,
        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;
                }
                //比较name
                int i = emp1.getName().compareTo(emp2.getName());
                if(i != 0) {
                    return i;
                }
                emp1.getBirthday().compareTo(emp2.getBirthday());
                //对birthday的比较,放在Date类比较好
//                //如果name相同,比较birthday -year
//                int yearMinus = emp1.getBirthday().getYear() - emp2.getBirthday().getYear();
//                    if(yearMinus != 0) {
//                        return yearMinus;
//                    }
//                    //如果year相同,比较month
//                int monthMinus = emp1.getBirthday().getMonth() - emp2.getBirthday().getMonth();
//                    if(monthMinus != 0) {
//                        return monthMinus;
//                    }
//                    //如果year和month 相同,比较day
                return emp1.getBirthday().getDay() - emp2.getBirthday().getDay();


            }
        });
        System.out.println("===对雇员进行排序==");
        System.out.println(employees);
    }
}
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) {//把对year-month-day比较
        //如果name相同,比较birthday -year
        int yearMinus = year - o.getYear();
        if(yearMinus != 0) {
            return yearMinus;
        }
        //如果year相同,比较month
        int monthMinus = month - o.getMonth();
        if(monthMinus != 0) {
            return monthMinus;
        }
        //如果year和month 相同,比较day
        return day - o.getDay();

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

    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 "\nEmployee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}
employees=[
Employee{name='tom', sal=20000.0, birthday=MyDate{year=2000, month=11, day=11}}, 
Employee{name='jack', sal=12000.0, birthday=MyDate{year=2001, month=12, day=12}}, 
Employee{name='hsp', sal=50000.0, birthday=MyDate{year=1980, month=10, day=10}}]
===对雇员进行排序===
===对雇员进行排序==
[
Employee{name='hsp', sal=50000.0, birthday=MyDate{year=1980, month=10, day=10}}, 
Employee{name='jack', sal=12000.0, birthday=MyDate{year=2001, month=12, day=12}}, 
Employee{name='tom', sal=20000.0, birthday=MyDate{year=2000, month=11, day=11}}]

五、自定义泛型

在这里插入图片描述

class Tiger<T, R, M> {
    String name;
    R r; //r属性使用泛型
    M m;
    T t;
    //因为数组在new 不能确定T的类型,就无法在内存开辟空间
    T[] ts;
    //T[] ts = new T[8];//错

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

在这里插入图片描述
这里是引用

interface IUsb<U, R> {
    //1.在接口中,静态成员也不能使用泛型
    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;
    }
}
//在继承接口 指定泛型接口的类型 U->String    R->Double
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) {

    }
}

在这里插入图片描述

public class CustomInterfaceGeneric {
    public static void main(String[] args) {
        Car car = new Car();
        car.fly("宝马" ,100);//当调用方法时,传入参数,编译器,就会确定类型
        /*
        * class java.lang.String
            class java.lang.Integer*/
        System.out.println("----------");
        car.fly(100, 10.1);
        /*
        * class java.lang.Integer
        class java.lang.Double
        * */
    }
}

//泛型方法,可以定义在普通类中,也可以定义在泛型类中
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) {}//R r是泛型类,K k是泛型方法//可以这样
}

这里是引用

在这里插入图片描述
这里是引用

六、泛型的继承和通配符

在这里插入图片描述
在这里插入图片描述

public class CustomInterfaceGeneric {
    public static void main(String[] args) {
        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<?>,可以接受任意的泛型类型
        printCollection1(list1);
        printCollection1(list2);
        printCollection1(list3);
        printCollection1(list4);
        printCollection1(list5);

        //List<? extends AA> c
        //printCollection2(list1);错
        //printCollection2(list2);错
        printCollection2(list3);
        printCollection2(list4);
        printCollection2(list5);

        //List<? super AA> c
        printCollection3(list1);
        //printCollection3(list2);错
        printCollection3(list3);
        //printCollection3(list4);错
        //printCollection3(list5);错
    }
    //List<?>表示任意泛型类型都可以接受
    public static void printCollection1(List<?> c) {
        for(Object object :c) {//通配符,取出时,就是Object
            System.out.println(object);
        }
    }
    // ?extends AA 表示 上限,可以接受AA或AA子类
    public static void printCollection2(List<? extends AA> c) {
        for (Object object :c) {
            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 CustomInterfaceGeneric {
    public static void main(String[] args) {

    }
    @Test
    public void testList() {
        //说明
        //这里我们给T指定类型是User
        DAO<User> dao = new DAO<>();
        dao.save("001", new User(1, 10, "jack"));
        dao.save("002", new User(2, 18, "king"));
        dao.save("003", new User(3, 38, "smith"));
        List<User> list = dao.list();
        System.out.println("list=" + list);//list=[User{id=1, age=10, name='jack'}, User{id=2, age=18, name='king'}, User{id=3, age=38, name='smith'}]

        dao.update("003", new User(3, 58, "milan"));
        list = dao.list();
        System.out.println("list=" + list);//list=[User{id=1, age=10, name='jack'}, User{id=2, age=18, name='king'}, User{id=3, age=58, name='milan'}]
        dao.delete("001");//删除
        System.out.println("id=003" + dao.get("003"));//获取、、id=003User{id=3, age=58, name='milan'}

    }
}

public class DAO<T> {
    private Map<String,T> map = new HashMap<>();
    public T get(String id) {
        return map.get(id);
    }
    public void update(String id, T entity) {
        map.put(id, entity);
    }
    //返回 map 中存放的所有T对象
    //遍历map[k-v],将map中的所有value(T entity),封装到ArrayList返回即可
    public List<T> list() {
        //创建 ArrayList
        List<T> list = new ArrayList<>();
        //遍历map
        Set<String> keySet = map.keySet();
        for (String key :keySet) {
            list.add(map.get(key));
        }
        return list;
    }
    public void delete(String id) {
        map.remove(id);
    }
    public void save(String id, T entity) {//把entity保存到map
        map.put(id, entity);
    }
}
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 + '\'' +
                '}';
    }
}
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方法被调用~");
    }
}

八、JUnit

在这里插入图片描述
在这里插入图片描述

    //传统方法
        new JUnit_().m1();
        new JUnit_().m2();
    }
    @Test
    public void m1() {
        System.out.println("m1方法被调用~");
    }
    @Test
    public void m2() {
        System.out.println("m2方法被调用~");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值