java泛型多重限定_Java泛型 - 多重界限( Multiple Bounds)

Java泛型 - 多重界限( Multiple Bounds)

类型参数可以有多个边界。

语法 (Syntax)public static > T maximum(T x, T y, T z)

哪里maximum - maximum是一种通用方法。

T - 传递给泛型方法的泛型类型参数。 它可以采取任何对象。

描述 (Description)

T是传递给泛型类Box的类型参数,应该是Number类的子类型,并且必须包含Comparable接口。 如果一个类以绑定方式传递,则应在接口之前首先传递它,否则将发生编译时错误。

例子 (Example)

使用您选择的任何编辑器创建以下Java程序。package com.iowiki;

public class GenericsTester {

public static void main(String[] args) {

System.out.printf("Max of %d, %d and %d is %d\n\n",

3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",

6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

}

public static

& Comparable> T maximum(T x, T y, T z) {

T max = x;

if(y.compareTo(max) > 0) {

max = y;

}

if(z.compareTo(max) > 0) {

max = z;

}

return max;

}

// Compiler throws error in case of below declaration

/* public static

& Number> T maximum1(T x, T y, T z) {

T max = x;

if(y.compareTo(max) > 0) {

max = y;

}

if(z.compareTo(max) > 0) {

max = z;

}

return max;

}*/

}

这将产生以下结果 -

输出 (Output)Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

有界类型参数(Bounded Type Parameters)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值