Lesson_for_java_day14--java中的泛型、Comparator、Comparable

2024-09-01 10:58

本文主要是介绍Lesson_for_java_day14--java中的泛型、Comparator、Comparable,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

泛型:

Demo1:

package generic;import java.util.ArrayList;
import java.util.Iterator;
/*泛型:JDK1.5版本以后出现的新特性,用于解决安全问题,是一个类型安全机制。好处:1、将运行时期出现的问题classCastException,转移到编译时期,方便于程序员解决问题。让运行事情问题减少,安全。2、避免了强制类型转换的麻烦。泛型格式:通过<>来定义要操作的的引用数据类型。在使用java提供的对象时,什么时候写泛型呢?通常在集合框架中很常见,只要定义到<>就要定义泛型。其实<>就是用来接收类型的。当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。*/
public class GenericDemo {public static void main(String[] args) {//<String>泛型,解决数据存储时的数据类型,防止出错ArrayList<String> al = new ArrayList<String>();al.add("abd01");al.add("a01");al.add("abd02");al.add("ab81");al.add("abd0174");for(Iterator<String> it = al.iterator();it.hasNext();){String s = it.next();           //不需要再强制类型转换了System.out.println(s + ":" + s.length());}		}
}

Demo2:

package generic;import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;public class GenericDemo2 {public static void main(String[] args) {// TODO Auto-generated method stubTreeSet<String> ts = new TreeSet<String>(new LenComparetor());ts.add("abd01");ts.add("a01");ts.add("abd02");ts.add("ab81");ts.add("abd0174");for(Iterator<String> it = ts.iterator();it.hasNext();){String s = it.next();           //不需要再强制类型转换了System.out.println(s);}		}
}class LenComparetor implements Comparator<String>{//使用泛型public int compare(String o1,String o2){//无需再强制类型转换int num = new Integer(o1.length()).compareTo(new Integer(o2.length()));if(num == 0)return o1.compareTo(o2);return num;}
}

Demo3:

package generic;public class GenericDemo3 {public static void main(String[] args) {//采用泛型机制,当类型输入异常时,编译时直接出错,提醒修改程序,提高安全性Utils<Worker> u = new Utils<Worker>();u.setObject(new Worker());Worker w = u.getObject();/*//当类型转换异常时,编译时不会出错,运行时才会抛出ClassCastException,这就降低了程序的安全性。Tool t = new Tool();t.setObject(new Student01());Worker w1 = (Worker)t.getObject();*/}
}//类1
class Worker{}//类2
class Student01{}/*泛型类什么时候需要定义泛型类?当类中要操作的引用数据类型不确定的时候,早期定义Object来完成扩展,现在定义泛型来完成扩展。
*/	
class Utils<QQ>{private QQ q;public void setObject(QQ q){this.q = q;}public QQ getObject(){return q;}
}//泛型出现之前操作
class Tool{private Object o;//向上转型,可复用性好,但是需要人为强制类型转换,容易出错public Object getObject() {return o;}public void setObject(Object o) {this.o = o;}	
}/*class Tool{private Worker w;//可复用性差public Worker getWorker() {return w;}public void setWorker(Worker w) {this.w = w;}	
}
*/

Demo4:

package generic;
/*泛型类定义的泛型,在整个类中有效,如果被方法使用,那么,泛型类的对象明确要操作的具体类型后,所以要操作的类型就已经固定了。为了让不同方法可以操作不同类型,而且类型还不确定,那么可以将类型定义在方法上。特殊之处:静态方法不可以访问类上定义的泛型。如果静态方法操作的引用数据类型不确定,可以将泛型定义在方法上。泛型位置:定义在类中,泛型在类名后面;定义在方法中,泛型在返回值前面。(书写格式)*///泛型定义在类上和方法上
public class GenericDemo4 {public static void main(String[] args) {/*方式一:Demo<Integer> d = new Demo<Integer>();d.show(4);d.print(new Integer(5));Demo<String> d1 = new Demo<String>();d1.show("hahaha");d1.print("hehehe");*//*方式二:Demo d = new Demo();d.show("hahah");d.show(new Integer(4));d.print("heihei");d.print(5);*///方式三:Demo<String> d = new Demo<String>();d.show("haha");d.print("heihei");d.print(9);Demo.method("lalalal");}
}//方式三:类上定义泛型,方法上也可以另外定义泛型。
class Demo<T>{public void show(T t){System.out.println("show:" + t);}public <Q>void print(Q q){System.out.println("print:" + q);}public static<W> void method(W w){System.out.println("method:" + w);}//静态方法不可以访问类上定义的泛型,可以将泛型定义在方法上
//	public static void method(T t){
//		System.out.println("method:" + t);
//	}
}/*方式二:泛型只定义在方法上
class Demo{public <T>void show(T t){System.out.println("show:" + t);}public <Q>void print(Q q){System.out.println("print:" + q);}
}
*//*方式一:方法与类的类型一致
class Demo<T>{public void show(T t){System.out.println("show:" + t);}public void print(T t){System.out.println("print:" + t);}
}
*/

Demo5:

package generic;
/*泛型定义在接口上:*/
public class GenericDemo5 {public static void main(String[] args) {/*方式一:调用者无需再指定类型InterImpl i = new InterImpl();i.show("hahaha");*///方式二:由调用者来指定泛型类型InterImpl<Integer> i = new InterImpl<Integer>();i.show(5);}
}//方式二:实现接口时也不知道泛型类型,保持与接口类型一致
class InterImpl<T> implements Inter<T>{public void show(T t){System.out.println("show:" + t);}
}/*方式一:实现接口时就指定类型
class InterImpl implements Inter<String>{public void show(String t){System.out.println("show:" + t);}
}
*/interface Inter<T>{void show(T t);
}

Demo6:

package generic;/*泛型:?为通配符。也可以理解为占位符。泛型的限定:? extends E: 可以接收E类型或者E的子类型。上限。? super E: 可以接收E类型或者E的父类型。下限。*/import java.util.ArrayList;
import java.util.Iterator;public class GenericDemo6 {public static void main(String[] args) {/*方式一:方式二:ArrayList<String> al = new ArrayList<String>();al.add("abd1");al.add("abd1");al.add("abd1");ArrayList<Integer> all = new ArrayList<Integer>();all.add(4);all.add(7);all.add(1);
*///方式一:不通用,printColl(all);不能操作//printColl(al);//方式二:使用?或T,定义通用泛型//printColl(al);//printColl(all);//方式三:限定泛型的类型为某一父类及其子类对象ArrayList<Student> al = new ArrayList<Student>();	al.add(new Student("abc---1"));al.add(new Student("abc---2"));al.add(new Student("abc---3"));printColl(al);}//方式三:限定泛型的类型为Person及其子类public static void printColl(ArrayList<? extends Person> al){for(Iterator<? extends Person> it = al.iterator();it.hasNext();){System.out.println(it.next().getName());}}
/*//方式二:定义泛型,可通用public static void printColl(ArrayList<?> al){for(Iterator<?> it = al.iterator();it.hasNext();){System.out.println(it.next());//不能使用对象特有的方法,如下例://it.next().length();}}//用?和用T的区别:
//	public static <T>void printColl(ArrayList<T> al){
//		for(Iterator<T> it = al.iterator();it.hasNext();){
//			T t = it.next();            //使用T可以接收对象,而使用?不可以接收对象。
//			System.out.println(it.next());
//		}
//	}
*/	/*方式一:定义泛型,但是不能通用public static void printColl(ArrayList<String> al){for(Iterator<String> it = al.iterator();it.hasNext();){System.out.println(it.next());}}*/}class Student extends Person{Student(){}Student(String name){super(name);}
}class Person{private String name;Person(){}Person(String name){this.name = name;}public String getName(){return name;}
}

Demo7:

package generic;import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;public class GenericDemo7 {public static void main(String[] args) {TreeSet<Student1> ts = new TreeSet<Student1>(new Comp());ts.add(new Student1("abc01"));ts.add(new Student1("abc02"));ts.add(new Student1("abc03"));ts.add(new Student1("abc04"));Iterator<Student1> it = ts.iterator();while(it.hasNext()){System.out.println(it.next().getName());}TreeSet<Worker1> ts1 = new TreeSet<Worker1>(new Comp());ts1.add(new Worker1("abc----01"));ts1.add(new Worker1("abc----02"));ts1.add(new Worker1("abc----03"));ts1.add(new Worker1("abc----04"));Iterator<Worker1> it1 = ts1.iterator();while(it1.hasNext()){System.out.println(it1.next().getName());}		}
}//泛型定义父类
class Comp implements Comparator<Person1>{public int compare(Person1 s1,Person1 s2){return s1.getName().compareTo(s2.getName());}
}class Student1 extends Person1{Student1(String name){super(name);}
}class Worker1 extends Person1{Worker1(String name){super(name);}
}class Person1{private String name;Person1(){}Person1(String name){this.name = name;}public String getName() {return name;}public String toString(){return "Person:" + name;}
}

这篇关于Lesson_for_java_day14--java中的泛型、Comparator、Comparable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1126738

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、