java项目中如何实现定义一个受限制的类型参数


作者:Leah

这篇文章将为大家详细讲解有关java项目中如何实现定义一个受限制的类型参数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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

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

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

package generics;
/**
* 定义受限制的方法
*
* @author psdxdgK1DT
*
*/
public class Box {
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 
* @param u
*/
public  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 integerBox = new Box();
integerBox.set(new Integer("some text"));
integerBox.inspect("some test");这里会出现预编译错误
integerBox.inspect(10);
}
}

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

java类是否必须有一个空参构造_java项目

如果强行编译则会报错: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 {
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:

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 { /* … */ } If bound A is not specified first, you get a compile-time error:
class D { /* … */ } // compile-time error

泛型算法

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

public static 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 interface:
public interface Comparable {
public int compareTo(T o);
}
The resulting code will be:
public static > int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
//因为这里的T是受限制的类型参数,实现了Comparable接口,于是可以使用接口的方法compareTo
if (e.compareTo(elem) > 0)
++count;
return count;
}

关于java项目中如何实现定义一个受限制的类型参数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。