Home >Java >javaTutorial >How to define restricted type parameters in java
[Related learning recommendations: java basic tutorial】
Sometimes you may want to limit the types that can be used as type parameters in a parameterized type . For example, a method that operates on numbers may only want to accept instances of Number or one of its subclasses. That's what bounded type parameters are for.
Method Examples for Restricted Parameter Types
To declare a bounded type parameter, list the name of the type parameter, followed by the extends keyword, then its upper limit, In this case Number
Note that in this case, extends is usually used to mean "extension" (as in a class) or "implementation" (as in an interface).
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); } }
A red wavy line will appear on the display to indicate a compilation error
If compilation is forced, an error will be reported:
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)
Translation:
Unresolved compilation error
Box class The inspect(U) method cannot be applied to (String) type parameters\
Classes using restricted type parameters can call restricted boundary methods
Except restrictions can be used for In addition to instantiating types of generic types, bounded type parameters also allow you to call methods defined in the boundary:
//使用受限类型参数的类 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 method calls the intValue method defined in the Integer class via n.
Multiple Bounds
The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:
dee20d5a101ff37576d3dea788a52029 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 6790247218b9dc5784654575b96adc6d { /* … */ } If bound A is not specified first, you get a compile-time error:
class D b08ac1cb90d2575d3d2e6d9d9e86e32d { /* … */ } // compile-time error
Generic algorithm
Bounded type parameters are the key to implementing generic algorithms. Consider the following method, which counts the number of elements in an array T[] that are greater than the specified element 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; }
Related learning recommendations: Programming video
The above is the detailed content of How to define restricted type parameters in java. For more information, please follow other related articles on the PHP Chinese website!