泛型

泛型

1、泛型的理解和好处

传统编写程序,在 ArrayList 中,添加三个 Dog 对象

对象包含 name和 age,并要求使用 get 方法输出 name 和 age

public class Generic{
    public static void main(String[] args){
        //使用传统的方法来解决
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Dog("旺财",10));
        arrayList.add(new Dog("发财",1));
        arrayList.add(new Dog("小黄",5));
        
        //遍历
        for (Object o : arrayList) {
            //向下转型 Object -> Dog 
            Dog dog=(Dog) o;
            System.out.println(dog.getName() + "+" +dog.getAge();
         }
           
                               
         //加入程序员,不小心加入一只猫
         arrayList.add(new Cat("小猫",10));                      
         //编译器没有报异常,但运行时会抛出异常                      
    }
}

                               
class Dog{
    private String name;
    private int age;
    
    public Dog(String name, int age){
    	this.name = name;
        this.age = age;
    }
    //get方法省略
}
class Cat{
    ......
}

使用传统方法的问题分析

1)不能对加入到集合 ArrayList 中的数据类型进行约束(不安全)

2)遍历的时候,需要进行类型转换(上显示为向下转型),如果集合中的数据量较大,对效率有影响

泛型解决问题

public class Generic{
    public static void main(String[] args){
        //使用泛型
        //解读
        //1.当我们 ArrayList<Dog> 表示存放到 ArrayList 集合中的元素是Dog类型
        //2.如果编译器发现添加的类型,不满足要求,就会报错
        //3.在遍历的时候,可以直接取出 Dog 类型而不是Object
        ArrayList<Dog> arrayList = new ArrayList<Dog>();
        arrayList.add(new Dog("旺财",10));
        arrayList.add(new Dog("发财",1));
        arrayList.add(new Dog("小黄",5));
        
        for (Dog dog : arrayList) {
            System.out.println(dog.getName() + "+" +dog.getAge();
         }
                          
    }
}

class Dog{
    ......//内容同上
}
class Cat{
    ......
}

2、泛型介绍

泛型 => Integer、String、Dog

  1. 泛型又称参数化类型,是 Jdk5.0 出现的新特性,解决数据类型的安全性问题

  2. 在类声明或实例化时只要指定好需要的具体的类型即可。

  3. Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生 ClassCastException 异常。同时,代码更加简洁、健壮

  4. 泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方法的返回值的类型,或者是参数类型。

    public class Generic{
        public static void main(String[] args){ 
            Person<String> strngPerson = new Person<String>("李四");            
        }
    }
    
    
    class Person<E>{  
        //用E来表示s的数据类型
        //s的数据类型是在定义Person对象时指定,即在编译期间,就确定E是什么类型
        E s; 
        
        public Person(E s){ //E也可以是参数类型
            this.s = s;
        }
        
        public E f(){ //返回类型使用E
            return s;
        }
    }
    

3、泛型的语法

泛型的声明

interface 接口{} 和 class 类<K , V>{}

//比如 : List, ArrayList

说明:

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

泛型的实例化:

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

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

泛型使用举例:

练习

创建三个学生对象

放进到 HashSet 中学生对象使用

放进到 HashMap 中,要求 key 是 String name, Value就是学生对象

使用两种方式遍历

public class TestGeneric2{
    public static void main(String[] args) {
        //1.HashSet
        HashSet<Student> students = new HashSet<Student>():
        students.add(new Student("john",12));
        students.add(new Student("tom",12));
        students.add(new Student("mary",12));
        
        //遍历
        for (Student student : students) {
            System.out.println(student);
         }
        
        
        //使用泛型方式给HashMap放入三个对象
        HashMap<String,student> hm = new HashMap<String, Student>();
        hm.put("tom",new Student("tom",12));
        hm.put("john",new Student("john",12));
        hm.put("mary",new Student("mary",12));
        
        //迭代器 EntrySet
        //因为在创建HashMap时有代替k,v,所以这里自动填充进k,v
        Set<Map.Entry<String,Student>> entries = hm.entrySet();
        Iterator<Map.Entry<String,Student>> iterator = entries.iterator();
        
        while (iterator.hasNext()){
            Map.Entry<String,Student> next = iterator.next():
            System.out.println(next.getKey() + next.getValue());
        }
        
    }
}
class Student {
    public String name;
    public int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    ...//get/set省略
}

注意事项:

  1. interface List{},public class HashSet{} ... 等等说明:T,E只能是引用类型

    //看看下面语句是否正确?
    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());
    pig<A> aPig2 = new Pig<A>(new B());
    
    class A {}
    class B extends A{}
    class Pig<E>{
        E e;
        public Pig(E e){
            this.e = e;
        }
    }
    
  3. 泛型使用形式

    ArrayList<Integer> list1 = new ArrayList<Integer>();
    List<Integer> list2 = new ArrayList<Integer>();
    //实际开发中,可以简写
    //编译器会进行类型推断,推荐以下写法
    ArrayList<Integer> list3 = new ArrayList<>();
    List<Integer> list4 = new ArrayList<>();
    
  4. 如果我们这样写 List list= new ArrayList() (或类似形式);默认泛型 就是 Object

4、泛型练习

定义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 Exercise{
    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)));
        
        //对雇员进行排序
        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;
                }
                
                //如果name相同,比较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();
                
                
            }
        });
    }
}
public class MyDate{
    private int year;
    private int month;
    private int day;
    //get/set方法,toString省略
}
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;
    }
    //get/set方法,toString省略
}

优化:把birthday的比较放到MyDate类完成

public class Exercise{
    public static void main(String[] args){
        //和前相同
        
        //对雇员进行排序
        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;
                }
                
                return emp1.getBirthday().compareTo(emp2.getBirthdat());
            }
        });
    }
}
public class MyDate implements Comparable<MyDate>{
    private int year;
    private int month;
    private int day;
    
    //get/set方法,toString省略
    
    @Override
    public int compareTo(MyDate o){
        //如果name相同,比较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{
    //和前相同
}

5、自定义泛型

自定义泛型类

基本语法:

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

注意细节:

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

自定义泛型类:

//老韩解读
//1.Tiger 后面泛型,所以我们把 Tiger 就称为自定义泛型类
//2,T,R,M泛型的标识符,一般是单个大写字母
//3.泛型标识符可以有多个。
//4.普通成员可以使用泛型(属性、方法)
//5.使用泛型的数组,不能初始化
//6.静态方法中不能使用类的泛型

class Tiger<T, R, M> {
    String name;
    R r;//属性使用泛型
    M m;
    T t;
    
    //T[] ts = new T[8];错误,不被允许
    //因为数组数组在new的时候,不能确定T的类型,就无法开辟空间
    
    public Tiger(String name, R r,M m,T t){//构造器使用泛型
        this.name = name;
        this.r = r;
        this.m = m;
        this.t = t;
    }
    
    //public static void m1(M m){}
    //错误,因为static的类要在加载时创建,但无法确定M的类型,JVM无法完成加载
    
    //方法使用泛型
    public R getR(){
        return r;
    }
    ...//其余get、set方法
}

练习:

//T=Double, R=String, M=Integer
Tiger<Double,String, Integer> g = new Tiger<>("john");

g.setT(10.9);//0K

//g.setT("yy");//错误,类型不对

System.out.println(g);

Tiger g2 = new Tiger("john~~");//0K 此时未指定,即T=Object R=Object M=Object 

g2.setT("yy");//0K,因为T = Object,"yy"=String 是Object子类

自定义泛型接口

基本语法:

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

注意细节:

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

案例:

interface IA extends IUsb<String,Integer>{}
//当去实现IA接口时,因为IA在继承IUsb,制定了U和R为String和Integer
//因此在实现IUsb方式时,用String和Double替换U和R
//注意:IA接口继承接口,所以AA要实现两个接口的方法
class AA implements MyInterface{ 
}


//实现接口时,直接指定泛型接口的类型
class BB implements IUsb<String,Integer>{}


//没有指定类型,默认为Object
class CC implements IUsb{}


interface Isb<U,R>{
	int n = 10;
    //U name;不能这样使用,接口中属性默认是public static final
    
    //普通方法中,可以使用接口泛型
    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...>返回类型 方法名(参数列表){
}

注意细节:

  1. 泛型方法,可以定义在普通类中,也可以定义在泛型类

    class Car{//普通类
        public void run(){//普通方法
        }
        
        public<T,R> void fly(T t, R r){//泛型方法
            //<T,R> 就是泛型
            //是提供给fly方法使用
        }
    }
    
    class Fish<T,R> {//泛型类
        public void run(){//普通方法
        }
        
        public<U,M> void eat(U u, M m){//泛型方法
            
        }
    }
    
  2. 当泛型方法被调用时,类型会确定

    Car car = new Car();
    car.fly("宝马",100);//当调用方法时,传入参数,编译器会确定类型
    car.fly(72.1,10);
    
  3. public void eat ( E e ) {} 方法不是泛型方法,修饰符后没有<T,R..> eat方法不是泛型方法,而是使用了泛型

  4. 泛型方法,可以使用类声明的泛型,也可以使用自己声明的泛型

练习:

下面的代码是否正确?错误请修改,并说出运行结果

class Apple<T,R,M>{//自定义泛型类
    public<E> void fly(E e){//泛型方法
    	System.out.println(e.getclass().getSimpleName());
    }
    //public void eat(U u) {}//错误,因为U没有声明,注销解决
    public void run(M m) {}
}
class Dog {}
    
//下面代码输出什么?
Apple<String, Integer, Double> apple = new Apple<>();
apple.fly(10);//10会被自动装箱 Integer10,输出Integer
apple.fly(new Dog());//Dog

6、泛型的继承和通配符

说明:

  1. 泛型不具备继承性

    List

posted @ 2025-09-08 23:16  lu璐  阅读(11)  评论(0)    收藏  举报