您现在的位置是:群英 > 开发技术 > 编程语言
java定义受限制的类型参数的方法是什么?
Admin发表于 2022-05-31 17:44:57824 次浏览
在实际案例的操作过程中,我们可能会遇到“java定义受限制的类型参数的方法是什么?”这样的问题,那么我们该如何处理和解决这样的情况呢?这篇小编就给大家总结了一些方法,具有一定的借鉴价值,希望对大家有所帮助,接下来就让小编带领大家一起了解看看吧。


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

有时您可能想限制可以在参数化类型中用作类型参数的类型。 例如,对数字进行操作的方法可能只希望接受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定义受限制的类型参数的方法是什么?的知识,欢迎关注群英网络,群英网络将为大家推送更多相关知识点的文章。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: 类型参数
相关信息推荐
2022-05-17 11:47:20 
摘要:android 倒计时一般实现方式:handler+postdelayed() 方式timer + timertask + handler 方式scheduledexecutorservice + h
2022-06-23 17:04:36 
摘要:大家在浏览网站时有没有注意到网站上有视频,音频等,正在学习HTML和CSS的小伙伴,你知道如何用HTML5在页面中插入视频并自动播放吗?这篇文章就和大家讲讲html5如何插入视频以及HTML插入视频的代码,感兴趣的小伙伴可以参考一下。
2022-07-11 17:49:22 
摘要:实现步骤:1、利用array_filter()函数过滤数组,将数组中的空元素删除,语法“array_filter(原数组)”,会返回一个过滤后的数组;2、利用count()函数获取原数组的长度和过滤后数组的长度;3、检查获取的两个数组长度是否相等,语法“原数组长度===过滤数组长度”,如果相等则数组元素均不为空,反之则有数组元素为空。
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部