java定义受限制的类型参数操作

所属分类: 软件编程 / java 阅读数: 49
收藏 0 赞 0 分享

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

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

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

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

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

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

如果强行编译则会报错:

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<T extends Integer> {

  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:

<T extends B1 & B2 & B3> 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 <T extends A & B & C> { /* … */ } If bound A is not specified first, you get a compile-time error:

class D <T extends B & A & C> { /* … */ } // compile-time error

泛型算法

有界类型参数是实现泛型算法的关键。考虑下面的方法,该方法计算数组T[]中大于指定元素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;
}

以上这篇java定义受限制的类型参数操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java输入输出流复制文件所用时间对比

这篇文章主要介绍了Java输入输出流复制文件所用时间对比的相关资料,非常不错,具有参考解决价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java线程中start和run方法全面解析

这篇文章主要介绍了Java线程中start和run方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java的JSON处理器fastjson使用方法详解

下面小编就为大家带来一篇Java的JSON处理器fastjson使用方法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Java 二维码,QR码,J4L-QRCode 的资料整理

本文主要介绍Java 中二维码,QR码,J4L-QRCode,这里整理了详细的资料供大家学习参考关于二维码的知识,有需要的小伙伴可以参考下
收藏 0 赞 0 分享

java哈夫曼树实例代码

这篇文章主要为大家介绍了java哈夫曼树实例代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android读取本地或网络图片并转换为Bitmap

这篇文章主要为大家详细介绍了Android读取本地或网络图片,并转换为Bitmap,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Java日期时间操作的方法

这篇文章主要为大家详细介绍了Java日期时间操作的一些方法,获得Calendar,定义日期/时间的格式等,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java 获取路径的各种方法(总结)

下面小编就为大家带来一篇java 获取路径的各种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java数据结构与算法之奇偶排序算法完整示例

这篇文章主要介绍了java数据结构与算法之奇偶排序算法,较为详细的分析了奇偶算法的原理并结合完整示例形式给出了实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

java数据结构与算法之双向循环队列的数组实现方法

这篇文章主要介绍了java数据结构与算法之双向循环队列的数组实现方法,结合实例形式分析了双向循环队列的原理与数组实现技巧,并附带说明了该算法的用途,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多