Java学习Day12 泛型简单学习

Java学习Day12 泛型简单学习

从传统方法到现代服

传统方法

/*
 *@author   yuhuw
 *@date     2023/10/8 5:42
 *@version  1.0
 */
/*
1)请编写程序,在ArrayList中,添加3个Dog对象
2) Dog对象含有name和age,并输出name和age(要求使用getName))
 */

public class ACompare {
    public static void main(String[] args) {
        //以下是传统方法
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Dog("hot",10));
        arrayList.add(new Dog("mae",10));
        arrayList.add(new Dog("sot",10));
        //若在程序中还有其他类 就会报错.ClassCastException
        arrayList.add(new Cat("eec",2));
        for (Object o :arrayList) {
            Dog dog = (Dog) o;
            System.out.println(dog.getName()+" "+dog.getAge());
        }

    }
}
//1.不能对加入到集合ArrayList数据类型进行约束,所以不安全
//2.遍历需要类型转换若数据大会影响效率
class Dog{
    private String name;
    private int 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;
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class Cat{

    private String name;
    private int 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;
    }

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

泛型

import java.util.ArrayList;

/*
 *@author   yuhuw
 *@date     2023/10/8 7:05
 *@version  1.0
 */
public class GenericNewDemo_Improve {
    public static void main(String[] args) {
        //以下是泛型 <>内代表存放元素类型 或其子类型 类型不同就会报错
        //遍历时直接取出Dog类型
        ArrayList<Dog> arrayList = new ArrayList<>();
        arrayList.add(new Dog("hot",10));
        arrayList.add(new Dog("mae",10));
        arrayList.add(new Dog("sot",10));
        //若在程序中还有其他类 就会报错.ClassCastException
        for (Dog dog :arrayList) {
            System.out.println(dog.getName()+" "+dog.getAge());
        }
        //1.编译时检查元素类型 提高安全性
        //2.减少类型转换
    }
}

泛型的作用

/*
 *@author   yuhuw
 *@date     2023/10/8 7:17
 *@version  1.0
 */
/*
1)泛型又称参数化类型,是Jdk5.0出现的新特性,解决数据类型的安全性问题
2)在类声明或实例化时只要指定好需要的具体的类型即可。
3) Java泛型可以保证如果程序在编译时没有发出警告,
运行时就不会产生ClassCastException异常。同时,代码更加简洁、健壮
4)泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,
或者是某个方法的返回值的类型,或者是参数类型。举例
 */
public class GenericExplanation {
    public static void main(String[] args) {
        Person<String> person =new Person<String>("yuhuw");//E是String
        person.show();
        Person<Integer> integerPerson = new Person<>(100);//E是Integer
        integerPerson.show();
        //E数据类型已经确定 在编译期间就已经确定
    }
}
//一个标识表示类中某个属性的类型
class Person<E>{
    //一个标识表示类中某个属性的类型
    E name;//用E表示name的数据类型 该数据类型是在定义Person的时候确定

    public Person(E name) {//E表示参数类型
        this.name = name;
    }
    public E f(){//E表示返回类型
        return name;
    }
    public void show(){
        System.out.println(name.getClass());
    }

}

泛型细节

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

/*
 *@author   yuhuw
 *@date     2023/10/8 10:07
 *@version  1.0
 */
public class GenericDetail {
    public static void main(String[] args) {
        List<Integer> integers = new ArrayList<>();
        //ArrayList<int> ints = new ArrayList<int>();
        // 1.错误 泛型的数据类型必须是引用类型不能是基本类型
        ArrayList<A> as = new ArrayList<>();
        Pig<A> aPig = new Pig<A>(new A());
        aPig.f();
        Pig<A> aPig2 = new Pig<A>(new B());
        aPig2.f();
        // 2.给泛型传入的数据类型可以是指定类型的子类型
        ArrayList<Integer> integers1 = new ArrayList<Integer>();
        ArrayList<Integer> integers2 = new ArrayList<>();
        // 3.泛型的使用形式 在实际开发中一般简写 编译器会进行类型推断 推荐使用简写
        ArrayList arrayList = new ArrayList();
        //等价ArrayList<Object> arrayList = new ArrayList<>();
        // 4.默认的写法 泛型默认是Object

    }
}
class Tiger<E>{
    E e;

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

Homework

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

/*
 *@author   yuhuw
 *@date     2023/10/8 13:32
 *@version  1.0
 */
/*
定义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需使用泛型来定义),对集合中的元素进行排序,并遍历输出:
排序方式:调用ArrayList 的sort方法,传入 Comparator对象[使用泛型],先按照name排序,如果name相同,则按生日日期的先后排序。
【即:定制排序】
有一定难度,比较经典泛型使用案例

 */
public class Homework01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        ArrayList<Emp> emps = new ArrayList<>();
        Emp emp1 = new Emp("alice",60000.56,new MyDate(2005,12,5));
        Emp emp2 = new Emp("lucy",80000.56,new MyDate(1999,2,23));
        Emp emp3 = new Emp("baby",90000.56,new MyDate(1999,8,15));
        emps.add(emp1);
        emps.add(emp2);
        emps.add(emp3);
        System.out.println(emps);
        emps.sort(new Comparator<Emp>() {
            @Override
            public int compare(Emp o1, Emp o2) {
                if (!(emp1 instanceof Emp && emp2 instanceof Emp)) {
                    System.out.println("类型不匹配");
                    return 0;
                }

//                //下面是对birthday的比较 最好放在MyDate类完成 提高封装性
//                if (o1.getName()).length()-(o2.getName()).length() == 0 {
//                    return (o1).getBirthday().getYear()-(o2).getBirthday().getYear();
//                } else if ((o1).getBirthday().getYear()-(o2).getBirthday().getYear() == 0) {
//                    return (o1).getBirthday().getMonth()-(o2).getBirthday().getMonth();
//                }
//                else if ((o1).getBirthday().getMonth()-(o2).getBirthday().getMonth() == 0){
//                    return (o1).getBirthday().getDay() - (o1).getBirthday().getDay();
//                }else {
//                return (o1.getName()).length()-(o2.getName()).length();}
                //以下是直接封装到类中的方法方便使用
                if ((o1.getName()).length()-(o2.getName()).length() != 0){
                    return (o1.getName()).length()-(o2.getName()).length();
                }
                return o1.getBirthday().compareTo(emp2.getBirthday());
            }
        });
        System.out.println(emps);
    }
}
class Emp{
    private String name;
    private double sal;
    private MyDate birthday;

    public Emp(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 "\nEmp{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}
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) {//以下是对birthday的比较封装
        int yearMin = year - o.getYear();
        if (yearMin != 0) {
            return yearMin;
        }
        int monthMin = month - o.getMonth();
        if (monthMin != 0) {
            return monthMin;
        }
        return  day - o.getDay();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值