泛型基本说明

这篇具有很好参考价值的文章主要介绍了泛型基本说明。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  1. 使用传统方法的问题分析
    1. 不能对加入到集合ArrayList中的数据类型进行约束(不安全)
    2. 遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响。
  2. 泛型的好处
    1. 编译时,检查添加元素的类型,提高了安全性
    2. 减少了类型转换的次数,提高效率
    3. 不在提示编译警告
    4. package com.hspedu.generic.improve;
      
      import java.util.ArrayList;
      
      /**
       * @author 韩顺平
       * @version 1.0
       */
      @SuppressWarnings({"all"})
      public class Generic02 {
          public static void main(String[] args) {
      
              //使用传统的方法来解决===> 使用泛型
              //老韩解读
              //1. 当我们 ArrayList<Dog> 表示存放到 ArrayList 集合中的元素是Dog类型 (细节后面说...)
              //2. 如果编译器发现添加的类型,不满足要求,就会报错
              //3. 在遍历的时候,可以直接取出 Dog 类型而不是 Object
              //4. public class ArrayList<E> {} E称为泛型,那么 Dog->E
              ArrayList<Dog> arrayList = new ArrayList<Dog>();
              arrayList.add(new Dog("旺财", 10));
              arrayList.add(new Dog("发财", 1));
              arrayList.add(new Dog("小黄", 5));
              //假如我们的程序员,不小心,添加了一只猫
              //arrayList.add(new Cat("招财猫", 8));
              System.out.println("===使用泛型====");
              for (Dog dog : arrayList) {
                  System.out.println(dog.getName() + "-" + dog.getAge());
              }
      
      
          }
      }
      
      /*
      1.请编写程序,在ArrayList 中,添加3个Dog对象
      2.Dog对象含有name 和 age, 并输出name 和 age (要求使用getXxx())
      3.老师使用泛型来完成代码
       */
      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 { //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;
          }
      }
      
  3. 泛型说明

    1. package com.hspedu.generic;
      
      import java.util.List;
      
      /**
       * @author 韩顺平
       * @version 1.0
       */
      public class Generic03 {
          public static void main(String[] args) {
      
              //注意,特别强调: E具体的数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
              Person<String> person = new Person<String>("韩顺平教育");
              person.show(); //String
      
              /*
                  你可以这样理解,上面的Person类
                  class Person {
                      String s ;//E表示 s的数据类型, 该数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
      
                      public Person(String s) {//E也可以是参数类型
                          this.s = s;
                      }
      
                      public String f() {//返回类型使用E
                          return s;
                      }
                  }
               */
      
              Person<Integer> person2 = new Person<Integer>(100);
              person2.show();//Integer
      
              /*
                  class Person {
                      Integer s ;//E表示 s的数据类型, 该数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型
      
                      public Person(Integer s) {//E也可以是参数类型
                          this.s = s;
                      }
      
                      public Integer f() {//返回类型使用E
                          return s;
                      }
                  }
               */
          }
      }
      
      //泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,
      // 或者是某个方法的返回值的类型,或者是参数类型
      
      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 show() {
              System.out.println(s.getClass());//显示s的运行类型
          }
      }
      

      E就代表你这个集合里的元素是什么类型的元素,而且必须是引用类型,不能是基本数据类型

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

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

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

  4. 泛型的语法

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

    2. 字母不代表值,而是数据类型

  5. 应用实例

    1. package com.jshedu.generic;
      
      import java.util.*;
      
      /**
       * @author Mr.jia
       * @version 1.0
       * 创建  3个学生对象
       * 放到HashSet中学生对象,要求Key是String name,Value就是学生对象
       */
      
      public class Generic02 {
          public static void main(String[] args) {
              HashSet<Student> students = new HashSet<Student>();
              students.add(new Student("jack",28));
              students.add(new Student("tom",23));
              students.add(new Student("lucy",26));
              //遍历
              for (Student o :students) {
                  System.out.println(o);
              }
              //使用泛型方式给HashMap放入3个学生,这个是两个参数的,
              //HashMap<String, Student>,传参时也要两个
              HashMap<String, Student> ssh = new HashMap<String, Student>();
              //迭代器里面的参数为什么会自动填充String,Student
              //定义HashMap的时候已经把k和V指定了
              ssh.put("tom",new Student("tom",58));
              ssh.put("king",new Student("king",48));
              ssh.put("rose",new Student("rose",38));
              //迭代器EntrySet
              Set<Map.Entry<String, Student>> entries = ssh.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{
          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 +
                      '}';
          }
      }
      

      注意自动填充是从HashMap的K和V来的

  6. 泛型注意事项

    1. E不能为基本数据类型,要求为引用类型

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

    3. 如果这样写泛型默认是Object 。ArrayList arrayList = new ArrayList();

    4. 等价ArrayList<Object> objects = new ArrayList<>();

  7. package com.jshedu.generic;
    
    import java.util.ArrayList;
    import java.util.Comparator;
    
    /**
     * @author Mr.jia
     * @version 1.0
     */
    
    public class Homework01 {
        public static void main(String[] args) {
            ArrayList<Employee> employees = new ArrayList<>();
            employees.add(new Employee("jack",12222,new MyDate(2023,4,17)));
            employees.add(new Employee("tomwaew",10000,new MyDate(2023,5,17)));
            employees.add(new Employee("tomwewewe",22222,new MyDate(2023,6,17)));
            
            System.out.println(employees);
    
            employees.sort(new Comparator<Employee>() {
                @Override
                public int compare(Employee o1, Employee o2) {
                    //先按照name排序,如果name相同,则按照生日日期
                    //先对传入的参数进行验证
                    if(!(o1 instanceof Employee && o2 instanceof Employee)){
                        System.out.println("类型不正确...");
                        return 0;
                    }
                    //比较name,这里是o1对象调用compareTo方法
                    //name是比较的字母谁在前,不是name的长度
                    int i = o1.getName().compareTo(o2.getName());
                    if(i !=0){
                        return i;
                    }
                    //如果name相同,就比较birthday-year
                    int yearMinus = o1.getBirthday().getYear()-o2.getBirthday().getYear();
                    if(yearMinus != 0){
                        return yearMinus;
                    }
                    //如果year相同,就比较month
                    int monthMinus = o1.getBirthday().getMonth()-o2.getBirthday().getMonth();
                    if(monthMinus != 0){
                        return monthMinus;
                    }
    
                    //year和month都相同
                    return o1.getBirthday().getDay()-o2.getBirthday().getDay();
    
                }
            });
            System.out.println("排序后=========");
            System.out.println(employees);
    
    
        }
    
    }
    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 +
                    '}';
        }
    }
    class MyDate{
        private int month;
        private int day;
        private int year;
    
        public MyDate(int year, int month, int day) {
            this.month = month;
            this.day = day;
            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;
        }
    
        public int getYear() {
            return year;
        }
    
        public void setYear(int year) {
            this.year = year;
        }
    
        @Override
        public String toString() {
            return "MyDate{" +
                    "month=" + month +
                    ", day=" + day +
                    ", year=" + year +
                    '}';
        }
    }
    

    Arrays.sort()底层代码,可以把年月日的比较封装到MyDate,MyDate接口实现Comparable<MyDate>,然后重写Comparable接口下的compareTo(MyDate o)方法

  8. 泛型基本说明

     文章来源地址https://www.toymoban.com/news/detail-417361.html

到了这里,关于泛型基本说明的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java中TreeSet的基本介绍,细节讨论,使用注意事项,常用方法,底层源码分析

    TreeSet 是 Java 中的一个有序集合实现,它基于红黑树数据结构来存储元素, 可以保持元素的自然顺序(默认情况下升序)或者根据自定义比较器来进行排序 。下面是关于 TreeSet 的基本介绍、细节讨论、使用注意事项、常用方法以及一些底层实现细节。 基本介绍: TreeSet 是

    2024年02月11日
    浏览(29)
  • 医学影像PACS系统源码: 三维重建基本后处理方法的介绍和说明

    多层面重建(MPR) 最大密度投影(MIP) 最小密度投影(MinIP) 表面阴影遮盖(SSD) 容积漫游技术(VRT) 曲面重建(CPR) 虚拟内镜技术(VE)   1、MPR MPR(Multi-Planar Reformatting),多平面重建,是将扫描范围内所有的轴位图像叠加起来再对某些标线标定的重组线所指定的组织进行

    2024年02月09日
    浏览(39)
  • Eigen库的基本使用说明(二)

     之前的文章中,简单的介绍了一些基本的操作,回归之前的内容可以参考一下链接: zEigen库的基本使用说明_每日亿学的博客-CSDN博客_eigen库  本章内容主要就是继续延伸Eigen库的使用内容也会实时进行更新,Eigen库在SLAM中使用广泛,需要对这个库有一定的熟悉。 首先最简单

    2023年04月22日
    浏览(26)
  • ScheduledThreadPoolExecutor 及 ThreadPoolExecutor的基本使用及说明

    关于作者:CSDN内容合伙人、技术专家, 从零开始做日活千万级APP。 专注于分享各领域原创系列文章 ,擅长java后端、移动开发、人工智能等,希望大家多多支持。 我们继续总结学习 Java基础知识 ,温故知新。 本文讲述 ScheduledThreadPoolExecutor 及 ThreadPoolExecutor。 我们并不推荐

    2024年02月15日
    浏览(29)
  • java中的方法返回值使用泛型,实现灵活的返回值类型

      使用Mybatis框架的时候,想封装一个底层JDBC控制器,用于提供和Mybatis交互的增删改查接口(公用的接口),但由于公用的查询方法可能是用户自定义的任意一个和表对应的java bean类型,所以要考虑怎么样给调用者返回正确的返回值类型,不需要调用者自己强转型的动作(例

    2024年02月06日
    浏览(41)
  • [WinForm开源]原神混池模拟器-蒙德篇:软件的基本介绍、使用方法、常见问题解决与代码开源

    首先先和各位旅行者道个歉,混池都过去这么久了才把软件开发好并发布出来 _ 创作目的: 为给各位旅行者(当然包括我自己)估测混池抽取的出货率以及让各位旅行者可以过手瘾,故开发了此项目作为参考。 创作说明: 该软件的一切结果仅可作为参考,并非游戏内所得结

    2024年04月08日
    浏览(85)
  • wordpress在安装使用中出现404、403、500及502问题的分析与解决方法

    前言 最近在使用WordPress的时候遇到了一些错误提示,相信大家在使用wordpress建立网站的时候,都会遇到一些问题,一般来说分为2种情况。 第一种情况是程序报错:程序报错一般会直接在网站顶部或者网站其他部分显示错误或者警告提示,如error:… 、Notice:….、 warning:…

    2024年02月01日
    浏览(26)
  • URI、URL、URIBuilder、UriBuilder、UriComponentsBuilder说明及基本使用

    之前想过直接获取url通过拼接字符串的方式实现,但是这种只是暂时的,后续地址如果有变化或参数很多,去岂不是要拼接很长,由于这些等等原因,所以找了一些方法实现 URI全称是Uniform Resource Identifier,也就是统一资源标识符,它是一种采用特定的语法标识一个资源的字符

    2024年02月11日
    浏览(29)
  • 股票基本面分析方法综述

    研究经济政策(货币政策、财政政策、产

    2024年02月11日
    浏览(20)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包