java 限制参数类型_java如何定义受限制的类型参数

56ef54bfbcb709fb0c900aacb99c1ddf.png

【相关学习推荐:java基础教程】

有时您可能想限制可以在参数化类型中用作类型参数的类型。 例如,对数字进行操作的方法可能只希望接受Number或其子类的实例。 这就是有界类型参数的用途。

受限制参数类型的方法示例

要声明有界类型参数,请列出类型参数的名称,后跟extends关键字,然后是其上限,在本例中为Number

请注意,在这种情况下,extends通常用于表示“扩展”(如在类中)或“实现”$ y * !(如在接口中)。

package generics;

/**

* 定义受限制的方法

*

* @au: L Z [ ? 6 * Qthor psdxdgK1DT

*

*/

public class Box&lt1 = 5 / [ v S P b;T> {

private T8 8 t % 4 g t;

public void set(T t) {

this.t% m } d = = t;

}

public T get() {

return t;

}

/**

* 通过修改我们的通用泛型方法以包含此有界类型参数,现在编译将失败,因为我们对inspect的调用仍包含String:

* By modifying? 7 i l H B ? q S our generic method to include this bounded type pa: J ?rameter

* compilation will now fail, si; ] / o t ( { &nce our invocation of in: c / , 1spect still includes a String:

* inspect:单词:检查

* @param &Z 4 $ B d j 0 Z 9lt;U>

* @param u

*/

public void inspect(U u) {

System.out.println("T:" + t.getClass().getName());

System.out.println("U:" + u.getClass().getName()8 f ;);

}

public static void main(String[] args) {

Box integerBox = new Box();

integerBox.set(new Integer("some text"));

integerBox.inspect("some test");这里会出现预编译错误

integerBox.i2 ^ y N 9 fnspect(10);

}

}

在显示器上会出现红色的波浪线表示编译错误

12f892ecb86726a63be4eea0042ab5ce.png

如果强行编译则会报错:

program run2 Q t G 8 V s result:

Exception in thread “main” java.lang.Error: Unresolved coa ^ Y ! @ P h + kmpilatK ) ~io[ l Tn problem: The mG = Q r X n Aethod inspeK s 7 * J a Ict(U) in the type Box is not applicable for the arguments (String)

at generics.Box.main(Box.& 4 = & &java:36)

译文:

未解决的编译错误

Box类的inspect(U)方法不可应用于(String)类型参数\

使用受限类型参的类可调用O } ) p $ $ I j受限边界方法

除了限制可用于实例化泛型类型的类型外,有界类型. b参数还允许您调用在边界中定义的方法:

//使用受限类型参数的类

public class NaturalNum; @ U g / 7 *ber {

privath ( X ) e U 4 +e T n;

public NaturalNud l D ; ) , L x dmber(T n) { this.n = n; }

publ2 - S S c r % Lic boolean isEven() {

return n.intValue() % 2 == 0;

}

// ...

isEven方法通过n调用Integer类中定义的intValue方法。

多重受限边界(Multiple BoundX , & ? &s)

The precedie J 8ng example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:

A type variable with multiple bounda y os is a4 + 9 . $ 1 & ) W subtype of all the types listed in the bound. If on4 _ Z = u # $e of the bounds is a class, it must be specified first. For example:

Class A { /* … / } interface B { / … / } interface C { / … */ }

class D

class D &l. l - ~ nt;g Q N | h . e e ]T extends B &a= k G Mmp; A & C> { /* … */ } // compile-time error

泛型算法

有界类型参数是实现泛型算法的关键。考虑下面的方法,该方法计算数3 n Z = e组T[]中大于指定元素elem的元素数。

public static int countGreaterThan(T[] anArray, T elem) {

i6 3 h U g V # }nt count = 0;

for (T e : anArray)

if (e > elem) // compiler error

++count;

return count;

}

The implementation of the method is straightfj t m o 4 w Korward,

but it does not compile be@ 9 S C Jcause 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 object: B ws. To fix the probM ? B Y % Wlem, use a type parameter

bounded by the Comparable interface:

public interq k 1 H # ~ L } ~face Comparable {

public int compareTo(T o);

}

The resulting code will be:

pui * 9blic static > int countGreaterThan(T[] anArrayP U 2 { K w /, T elem) {

int count = 0;

for (T e : anArray)

/F m P/因为这里的T是受限制的类型参+ x % d 7 Z y G S数,实现了Comparable接口,于是可以使用接口的方法compareTo

if (/ r %e.compareTo(elem) > 0)

++count;

return count;

}相关学习推荐:编程视频

以上就是java如何定义受限制的类型参数的详细内容。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值