java定义受限制的类型参数操作
作者:占东红 发布时间:2022-12-16 09:44:03
有时您可能想限制可以在参数化类型中用作类型参数的类型。 例如,对数字进行操作的方法可能只希望接受Number或其子类的实例。 这就是有界类型参数的用途。
受限制参数类型的方法示例
要声明有界类型参数,请列出类型参数的名称,后跟extends关键字,然后是其上限,在本例中为Number
请注意,在这种情况下,extends通常用于表示“扩展”(如在类中)或“实现”(如在接口中)。
package generics;
/**
* 定义受限制的方法
*
* @author psdxdgK1DT
*
*/
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
/**
* 通过修改我们的通用泛型方法以包含此有界类型参数,现在编译将失败,因为我们对inspect的调用仍包含String:
* By modifying our generic method to include this bounded type parameter
* compilation will now fail, since our invocation of inspect still includes a String:
* inspect:单词:检查
* @param <U>
* @param u
*/
public <U extends Number> void inspect(U u) {
System.out.println("T:" + t.getClass().getName());
System.out.println("U:" + u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.set(new Integer("some text"));
integerBox.inspect("some test");这里会出现预编译错误
integerBox.inspect(10);
}
}
在显示器上会出现红色的波浪线表示编译错误
如果强行编译则会报错:
program run result:
Exception in thread “main” java.lang.Error: Unresolved compilation problem: The method inspect(U) in the type Box is not applicable for the arguments (String)
at generics.Box.main(Box.java:36)
译文:
未解决的编译错误
Box类的inspect(U)方法不可应用于(String)类型参数\
使用受限类型参的类可调用受限边界方法
除了限制可用于实例化泛型类型的类型外,有界类型参数还允许您调用在边界中定义的方法:
//使用受限类型参数的类
public class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) { this.n = n; }
public boolean isEven() {
return n.intValue() % 2 == 0;
}
// ...
}
isEven方法通过n调用Integer类中定义的intValue方法。
多重受限边界(Multiple Bounds)
The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:
<T extends B1 & B2 & B3> A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:
Class A { /* … / } interface B { / … / } interface C { / … */ }
class D <T extends A & B & C> { /* … */ } If bound A is not specified first, you get a compile-time error:
class D <T extends B & A & C> { /* … */ } // compile-time error
泛型算法
有界类型参数是实现泛型算法的关键。考虑下面的方法,该方法计算数组T[]中大于指定元素elem的元素数。
public static <T> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e > elem) // compiler error
++count;
return count;
}
The implementation of the method is straightforward,
but it does not compile because the greater than operator (>) applies only to primitive types
such as short, int, double, long, float, byte, and char.
You cannot use the > operator to compare objects. To fix the problem, use a type parameter
bounded by the Comparable<T> interface:
public interface Comparable<T> {
public int compareTo(T o);
}
The resulting code will be:
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
//因为这里的T是受限制的类型参数,实现了Comparable接口,于是可以使用接口的方法compareTo
if (e.compareTo(elem) > 0)
++count;
return count;
}
来源:https://blog.csdn.net/qq_30906791/article/details/108118570


猜你喜欢
- 目录一、抽象类1.抽象类概述1.1 为什么要有抽象类?(抽象类的作用)1.2 抽象类的定义2. 抽象类特点3.抽象类成员特点4.抽象类案例二
- 上次老师跟大家分享了 cookie、session和token,今天给大家分享一下Java 8中的Stream API。Stream简介1、
- 一、二叉搜索树插入元素/** * user:ypc; * date:2021-05-18; * time: 15:09; */
- ////////////////////////////
- 当一个结合中想根据某一个字段做去重方法时使用以下代码IQueryable 继承自IEnumerable先举例:#region linq to
- Java单例模式的实现,对java 单例模式的几种实现方法进行了整理:单例模式好多书上都是这么写的:public class SingleT
- 1.Mybatis的Dao层实现1.1 传统开发方式1.1.1编写UserDao接口public interface UserDao { &
- 1.打开File >> setting,选择Plugins>>Browse Repositories2.搜索Jreb
- 一、前言java是一门跨硬件平台的面向对象高级编程语言,java程序运行在java虚拟机上(JVM),由JVM管理内存,这点是和C++最大区
- 环境搭建项目结构图:1.我们首先做好服务端pom.xml<dependencies>
- ##创建测试类 新建Java工程创建测试类如下代码:(创建文件验证定时器是否执行)package makeFile;import java.
- C++的 bitset 在 bitset 头文件中,它是一种类似数组的结构,它的每一个元素只能是0或1,每个元素仅用1bit空间。下面是具体
- 创建WebService项目首先安装下.NET Framework4.6.2-4.7.1开发工具。然后就是新建 ASP.NET Web应用程
- 这里简单介绍一下ZXing库。ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。
- 通过配置变量调用配置文件url1.application.yml 配置文件配置参数feign: sys: http://127.
- 最近遇到的一个场景,在一个被 @Transactional 注解的方法A中中调用了一个被 @Async 注解标记的方法B,由于方法B 在执行
- 使用DOM4J方式生成XML文件的步骤如下:引入JAR包通过DocumentHelper类的createDocument()创建Docume
- 本文实例为大家分享了Android实现串口通信的具体代码,供大家参考,具体内容如下生成so文件首先确保已经安装了NDK和CMake然后创建一
- IntelliJ IDEA一个吸引人的地方在于,他有比较好的反编译工具,这让Eclipse用户牙痒痒。但不要紧,本文介绍如何在Eclipse
- 一、程序的三种结构顺序结构分支结构循环结构二、条件语句if 语句是最有用的控制结构之一。 if … else …语句的语法:if (布尔表达