【Java】—— 泛型:泛型的理解及其在集合(List,Set)、比较器(Comparator)中的使用

目录

1. 泛型概述

1.1 生活中的例子

1.2 泛型的引入

2. 使用泛型举例

2.1 集合中使用泛型

2.1.1 举例

2.1.2 练习

2.2 比较器中使用泛型

2.2.1 举例

2.2.2 练习


1. 泛型概述

1.1 生活中的例子

  • 举例1:中药店,每个抽屉外面贴着标签

  • 举例2:超市购物架上很多瓶子,每个瓶子装的是什么,有标签

  • 举例3:家庭厨房中:

Java中的泛型,就类似于上述场景中的标签

1.2 泛型的引入

        在Java中,我们在声明方法时,当在完成方法功能时如果有未知的数据需要参与,这些未知的数据需要在调用方法时才能确定,那么我们把这样的数据通过形参表示。在方法体中,用这个形参名来代表那个未知的数据,而调用者在调用时,对应的传入实参就可以了。

        受以上启发,JDK1.5设计了泛型的概念。泛型即为“类型参数”,这个类型参数在声明它的类、接口或方法中,代表未知的某种通用类型。

举例1:

        集合类在设计阶段/声明阶段不能确定这个容器到底实际存的是什么类型的对象,所以在JDK5.0之前只能把元素类型设计为Object,JDK5.0时Java引入了“参数化类型(Parameterized type)”的概念,允许我们在创建集合时指定集合元素的类型。比如List<String>,这表明该List只能保存字符串类型的对象。

        使用集合存储数据时,除了元素的类型不确定,其他部分是确定的(例如关于这个元素如何保存,如何管理等)。

举例2:

  java.lang.Comparable接口和java.util.Comparator接口,是用于比较对象大小的接口。这两个接口只是限定了当一个对象大于另一个对象时返回正整数,小于返回负整数,等于返回0,但是并不确定是什么类型的对象比较大小。JDK5.0之前只能用Object类型表示,使用时既麻烦又不安全,因此 JDK5.0 给它们增加了泛型。

其中<T>就是类型参数,即泛型。

所谓泛型,就是允许在定义类、接口时通过一个标识表示类中某个属性的类型或者是某个方法的返回值或参数的类型。这个类型参数将在使用时(例如,继承或实现这个接口、创建对象或调用方法时)确定(即传入实际的类型参数,也称为类型实参)。

2. 使用泛型举例

        自从JDK5.0引入泛型的概念之后,对之前核心类库中的API做了很大的修改,例如:JDK5.0改写了集合框架中的全部接口和类、java.lang.Comparable接口、java.util.Comparator接口、Class类等。为这些接口、类增加了泛型支持,从而可以在声明变量、创建对象时传入类型实参。

2.1 集合中使用泛型

2.1.1 举例

集合中没有使用泛型时:

集合中使用泛型时:

Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException异常。即,把不安全的因素在编译期间就排除了,而不是运行期;既然通过了编译,那么类型一定是符合要求的,就避免了类型转换。

同时,代码更加简洁、健壮。

把一个集合中的内容限制为一个特定的数据类型,这就是generic背后的核心思想。

举例:

//泛型在List中的使用
@Test
public void test1(){//举例:将学生成绩保存在ArrayList中//标准写法://ArrayList<Integer> list = new ArrayList<Integer>();//jdk7的新特性:类型推断ArrayList<Integer> list = new ArrayList<>();list.add(56); //自动装箱list.add(76);list.add(88);list.add(89);//当添加非Integer类型数据时,编译不通过//list.add("Tom");//编译报错Iterator<Integer> iterator = list.iterator();while(iterator.hasNext()){//不需要强转,直接可以获取添加时的元素的数据类型Integer score = iterator.next();System.out.println(score);}
}

举例:

//泛型在Map中的使用
@Test
public void test2(){HashMap<String,Integer> map = new HashMap<>();map.put("Tom",67);map.put("Jim",56);map.put("Rose",88);//编译不通过//        map.put(67,"Jack");//遍历key集Set<String> keySet = map.keySet();for(String str:keySet){System.out.println(str);}//遍历value集Collection<Integer> values = map.values();Iterator<Integer> iterator = values.iterator();while(iterator.hasNext()){Integer value = iterator.next();System.out.println(value);}//遍历entry集Set<Map.Entry<String, Integer>> entrySet = map.entrySet();Iterator<Map.Entry<String, Integer>> iterator1 = entrySet.iterator();while(iterator1.hasNext()){Map.Entry<String, Integer> entry = iterator1.next();String key = entry.getKey();Integer value = entry.getValue();System.out.println(key + ":" + value);}}
2.1.2 练习

练习1:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.function.Predicate;public class TestNumber {public static void main(String[] args) {ArrayList<Integer> coll = new ArrayList<Integer>();Random random = new Random();for (int i = 1; i <= 5 ; i++) {coll.add(random.nextInt(100));}System.out.println("coll中5个随机数是:");for (Integer integer : coll) {System.out.println(integer);}//方式1:使用集合的removeIf方法删除偶数coll.removeIf(new Predicate<Integer>() {@Overridepublic boolean test(Integer integer) {return integer % 2 == 0;}});//方式2:调用Iterator接口的remove()方法//Iterator<Integer> iterator1 = coll.iterator();//while(coll.hasNext()){//    Integer i = coll.next();//   if(i % 2 == 0){//       coll.remove();//    }//}System.out.println("coll中删除偶数后:");Iterator<Integer> iterator = coll.iterator();while(iterator.hasNext()){Integer number = iterator.next();System.out.println(number);}}
}

2.2 比较器中使用泛型

2.2.1 举例
public class Circle{private double radius;public Circle(double radius) {super();this.radius = radius;}public double getRadius() {return radius;}public void setRadius(double radius) {this.radius = radius;}@Overridepublic String toString() {return "Circle [radius=" + radius + "]";}}

使用泛型之前:

import java.util.Comparator;class CircleComparator implements Comparator{@Overridepublic int compare(Object o1, Object o2) {//强制类型转换Circle c1 = (Circle) o1;Circle c2 = (Circle) o2;return Double.compare(c1.getRadius(), c2.getRadius());}
}
//测试:
public class TestNoGeneric {public static void main(String[] args) {CircleComparator com = new CircleComparator();System.out.println(com.compare(new Circle(1), new Circle(2)));System.out.println(com.compare("圆1", "圆2"));//运行时异常:ClassCastException}
}

使用泛型之后:

import java.util.Comparator;class CircleComparator1 implements Comparator<Circle> {@Overridepublic int compare(Circle o1, Circle o2) {//不再需要强制类型转换,代码更简洁return Double.compare(o1.getRadius(), o2.getRadius());}
}//测试类
public class TestHasGeneric {public static void main(String[] args) {CircleComparator1 com = new CircleComparator1();System.out.println(com.compare(new Circle(1), new Circle(2)));//System.out.println(com.compare("圆1", "圆2"));//编译错误,因为"圆1", "圆2"不是Circle类型,是String类型,编译器提前报错,//而不是冒着风险在运行时再报错。}
}
2.2.2 练习

MyDate.jave

package exer1;/*** ClassName:IntelliJ IDEA* Description:*      2、MyDate类包含:*      private成员变量year,month,day,并为每一个属性定义getter、setter方法* @Author zyjstart* @Create:2024/10/5 16:02*/
public class MyDate {private int year;private int month;private int day;public MyDate() {}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;}@Overridepublic String toString() {return year + "年" + month + "月" + day + "日";}
}

Employee.java

package exer1;/*** ClassName:IntelliJ IDEA* Description:*      1、定义一个Employee类:*      该类包含:private成员变量name,age,birthday,其中birthday为MyDate类的对象:*      并为每一个属性定义getter,setter方法*      并重写toString方法输出name,age,birthday* @Author zyjstart* @Create:2024/10/5 16:00*/
public class Employee implements Comparable<Employee>{private String name;private int age;private MyDate birthday;public Employee() {}public Employee(String name, int age, MyDate birthday) {this.name = name;this.age = age;this.birthday = birthday;}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 MyDate getBirthday() {return birthday;}public void setBirthday(MyDate birthday) {this.birthday = birthday;}@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", age=" + age +", birthday=" + birthday +'}';}//按照name从高到低排序@Overridepublic int compareTo(Employee o) {return this.name.compareTo(o.name);}
}

EmployeeTest.java

package exer1;import org.junit.Test;import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;/*** ClassName:IntelliJ IDEA* Description:*      3、创建该类的5个对象,并把这些对象放入TreeSet集合中(TreeSet 需使用泛型来定义)**      4、分别按以下两种方式对集合中的元素进行排序,并遍历输出:*          1)、使Employee实现Comparable接口,并按name排序*          2)、创建TreeSet时传入Comparator对象,按生日日期的先后排序* @Author zyjstart* @Create:2024/10/5 16:05*/
public class EmployeeTest {//1)、使Employee实现Comparable接口,并按name排序@Testpublic void test1(){TreeSet<Employee> set = new TreeSet<>();Employee e1 = new Employee("Hanmeimei",18,new MyDate(1998,12,16));Employee e2 = new Employee("Gaoqiqi",25,new MyDate(2002,11,19));Employee e3 = new Employee("Daleiju",34,new MyDate(1944,6,24));Employee e4 = new Employee("Zixianxina",17,new MyDate(1999,8,27));Employee e5 = new Employee("Yinana",37,new MyDate(2011,1,31));set.add(e1);set.add(e2);set.add(e3);set.add(e4);set.add(e5);//遍历Iterator<Employee> iterator = set.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}}//2)、创建TreeSet时传入Comparator对象,按生日日期的先后排序@Testpublic void test2() {Comparator<Employee> comparator = new Comparator<Employee>() {@Overridepublic int compare(Employee o1, Employee o2) {// 先比较年int yearDistince = o1.getBirthday().getYear() - o2.getBirthday().getYear();if (yearDistince != 0){ // 如果年份不相等,返回结果,相等,则判断月份return yearDistince;}// 比较月int monthDistince = o1.getBirthday().getMonth() - o2.getBirthday().getMonth();if (monthDistince != 0){return monthDistince;}return o1.getBirthday().getDay() - o2.getBirthday().getDay();}};TreeSet<Employee> set = new TreeSet<>(comparator);Employee e1 = new Employee("Hanmeimei",18,new MyDate(1999,12,16));Employee e2 = new Employee("Gaoqiqi",25,new MyDate(2002,11,19));Employee e3 = new Employee("Daleiju",34,new MyDate(1944,6,24));Employee e4 = new Employee("Zixianxina",17,new MyDate(1999,8,27));Employee e5 = new Employee("Yinana",37,new MyDate(2011,1,31));set.add(e1);set.add(e2);set.add(e3);set.add(e4);set.add(e5);//遍历Iterator<Employee> iterator = set.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}}
}

在EmployeeTest.java中有两个测试方法,分别对应两个目标要求

test1按姓名排序,输出

test2按出生年月排序,输出

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1555441.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【JavaEE】——文件IO

阿华代码&#xff0c;不是逆风&#xff0c;就是我疯 你们的点赞收藏是我前进最大的动力&#xff01;&#xff01; 希望本文内容能够帮助到你&#xff01;&#xff01; 目录 一&#xff1a;认识文件 1&#xff1a;文件的概念 2&#xff1a;文件的结构 3&#xff1a;文件路径…

【操作系统】体系结构

&#x1f339;&#x1f60a;&#x1f339;博客主页&#xff1a;【Hello_shuoCSDN博客】 ✨操作系统详见 【操作系统专项】 ✨C语言知识详见&#xff1a;【C语言专项】 目录 操作系统的内核 操作系统结构——分层结构 操作系统结构——模块化 操作系统结构——宏内核、微内核…

修改Anaconda虚拟环境默认安装路径(Linux系统)

文章目录 修改Anaconda虚拟环境默认安装路径(Linux系统)1.方法一&#xff1a;使用--prefix参数2.方法二&#xff1a;配置conda环境的默认安装位置 修改Anaconda虚拟环境默认安装路径(Linux系统) 1.方法一&#xff1a;使用--prefix参数 在创建虚拟环境时&#xff0c;使用--pre…

BUSHOUND的抓包使用详解

BUSHOUND是个过滤软件&#xff0c;确切来说是在windows操作系统它的驱动层USB传输的数据。所以这个数据上可能是与USB的总线上的数据是有一点差异的。 先要选择设备的抓包。所以就是在device这个界面底下&#xff0c;我们首先要选择我们要抓的设备。 尝试下键盘设备 电脑键盘…

【可视化大屏】将柱状图引入到html页面中

到这里还是用的死数据&#xff0c;先将柱状图引入html页面测试一下 根据上一步echarts的使用步骤&#xff0c;引入echarts.js后需要初始化一个实例对象&#xff0c;所以新建一个index.js文件来进行创建实例化对象和配置数据信息等。 //在index.html引入<script src"j…

Python爬虫使用实例-mdrama

一个Python爬虫使用实例&#xff1a;主要用于下载指定的剧集音频。分别从网页和json文件中获取剧集的title和剧集中所存在音频的id&#xff0c;调用you-get&#xff0c;最后自动重命名下载文件夹为剧集名title。 目标网址&#xff1a; https://www.missevan.com/mdrama/其中为…

开源AI智能名片小程序源码:私域电商构建独特竞争力的新机遇

摘要&#xff1a;本文旨在探讨私域电商如何利用开源AI智能名片小程序源码构建独特竞争力。在强调独特性是通向成功的必要条件的基础上&#xff0c;分析开源AI智能名片小程序源码在私域电商发展独特性方面的作用及相关策略。 一、引言 在竞争激烈的商业环境中&#xff0c;让自己…

RTX4060安装nvidia显卡驱动

文章目录 nvidia drivers下载删除原有nvidia驱动安装nvidia驱动如果报错Unable to find the kernel source tree for the currently runningbuilding kernel modules解决方法 报错成功安装!!! nvidia drivers下载 https://www.nvidia.cn/geforce/drivers/#:~:textNVIDIA%20GeF…

Python从入门到高手5.1节-Python简单数据类型

目录 5.1.1 理解数据类型 5.1.2 Python中的数据类型 5.1.3 Python简单数据类型 5.1.4 特殊的空类型 5.1.5 Python变量的类型 5.1.6 广州又开始变热 5.1.1 理解数据类型 数据类型是根据数据本身的性质和特征来对数据进行分类&#xff0c;例如奇数与偶数就是一种数据类型。…

去噪扩散模型

Denoising Diffusion Probabilistic Models 图像扩散模型是一种生成模型&#xff0c;它基于概率扩散过程来生成新的图像。 核心步骤包括&#xff1a;&#xff08;1&#xff09;前向扩散过程&#xff1b;&#xff08;2&#xff09;逆向扩散过程 前向扩散过程&#xff08;正向过…

No.4 笔记 | 探索网络安全:揭开Web世界的隐秘防线

在这个数字时代&#xff0c;网络安全无处不在。了解Web安全的基本知识&#xff0c;不仅能保护我们自己&#xff0c;也能帮助我们在技术上更进一步。让我们一起深入探索Web安全的世界&#xff0c;掌握那些必备的安全知识&#xff01; 1. 客户端与WEB应用安全 前端漏洞&#xff1…

Spring Boot框架下的大学生就业招聘平台

5系统详细实现 5.1 用户模块的实现 5.1.1 求职信息管理 大学生就业招聘系统的用户可以管理自己的求职信息&#xff0c;可以对自己的求职信息添加修改删除操作。具体界面的展示如图5.1所示。 图5.1 求职信息管理界面 5.1.2 首页 用户登录可以在首页看到招聘信息展示也一些求职…

STM32中断——外部中断

目录 一、概述 二、外部中断&#xff08;Extern Interrupt简称EXTI&#xff09; 三、实例-对射式红外传感器 1、配置中断&#xff1a; 2 、完整代码 一、概述 中断&#xff1a;在主程序运行过程中&#xff0c;出现了特定的中断触发条件(中断源)&#xff0c;使得CPU暂停当…

【图论】树剖(上):重链剖分

一、前置知识清单 深度优先搜索DFS 点我复习图的存储 复习链接敬请期待树状数组 点我复习 二、树剖简介 树剖&#xff08;树链剖分&#xff09;&#xff0c;是一种把树划分成链的算法&#xff0c;该算法分为重链剖分和长链剖分。 本文仅讨论重链剖分&#xff0c;长链剖分目前…

MySQL联合索引、索引下推Demo

1.联合索引 测试SQL语句如下&#xff1a;表test中共有4个字段(id, a, b, c)&#xff0c;id为主键 drop table test;#建表 create table test(id bigint primary key auto_increment,a int,b int,c int )#表中插入数据 insert into test(a, b, c) values(1,2,3),(2,3,4),(4,5,…

算法修炼之路之滑动窗口

目录 一&#xff1a;滑动窗口的认识及模板 二&#xff1a;LeetcodeOJ练习 1.第一题 2.第二题 3.第三题 4.第四题 5.第五题 6.第六题 7.第七题 一&#xff1a;滑动窗口的认识及模板 这里先通过一道题来引出滑动窗口 LeetCode 209 长度最小的子数组 画图分析&…

aws(学习笔记第一课) AWS CLI,创建ec2 server以及drawio进行aws画图

aws(学习笔记第一课) 使用AWS CLI 学习内容&#xff1a; 使用AWS CLI配置密钥对创建ec2 server使用drawio&#xff08;vscode插件&#xff09;进行AWS的画图 1. 使用AWS CLI 注册AWS账号 AWS是通用的云计算平台&#xff0c;可以提供ec2&#xff0c;vpc&#xff0c;SNS以及clo…

使用 Python 遍历文件夹

要解决这个问题&#xff0c;使用 Python 的标准库可以很好地完成。我们要做的是遍历目录树&#xff0c;找到所有的 text 文件&#xff0c;读取内容&#xff0c;处理空行和空格&#xff0c;并将处理后的内容合并到一个新的文件中。 整体思路&#xff1a; 遍历子目录&#xff1…

2.3MyBatis——插件机制

2.3MyBatis——插件机制 1.基本用法2.原理探究2.1加载过程2.2执行过程2.2.1 插件的执行点2.2.2 SQL执行的几个阶段2.2.3 如何梳理出执行流程 插件机制是一款优秀框架不可或缺的组成部分&#xff0c;比如spring、dubbo&#xff0c;还有我们要聊的Mybatis等等。所谓插件&#xff…

vSAN02:容错、存储策略、文件服务、快照与备份、iSCSI

目录 vSAN容错条带化存储策略1. 创建新策略2. 应用存储策略 vSAN文件服务文件服务快照与备份 vSAN iSCSI目标服务 vSAN容错 FTT&#xff1a;Fault to Tolerance 允许故障数 故障域&#xff1a;每一台vSAN主机是一个故障域 - 假设3台超融合&#xff08;3计算1存储&#xff09;&…