java 有界泛型_Java泛型有界类型参数

有时候您可能希望限制允许传递给类型参数的类型。 例如,对数字进行操作的方法可能只希望接受Number类或其子类的实例。这样的参考限制称为:有界类型参数。

要声明一个有界类型参数,列出类型参数名称,后跟extends关键字,后跟其边界上限。

示例

以下示例说明如何在一般意义上使用extends来表示“扩展”(如在类中)或“实现”(如在接口中)。 这个例子是泛型方法返回最大的三个Comparable对象 -

使用您喜欢的编辑器创建以下java程序,并保存到文件:BoundedTypeParameters.java 中,代码如下所示 -

public class BoundedTypeParameters {

// determines the largest of three Comparable objects

public static > T maximum(T x, T y, T z) {

T max = x; // assume x is initially the largest

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

max = y; // y is the largest so far

}

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

max = z; // z is the largest now

}

return max; // returns the largest object

}

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));

System.out.printf("Max of %s, %s and %s is %s\n", "pear", "apple",

"orange", maximum("pear", "apple", "orange"));

}

}

执行上面代码,得到以下结果 -

D:\>javac BoundedTypeParameters.java

D:\>java BoundedTypeParameters

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

b739ec46bb5c46d9c0aa4ce35ba1ea56.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值