java方法采用T extends Number
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java方法采用T extends Number,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2291字,纯文字阅读大概需要4分钟。
内容图文
我有点生疏,陷入了一些基本问题.我希望我的方法printBinary可以采用Long或Integer.并基于输入类型我想调用相应的Object的toBinaryString()方法.
现在我知道有一些替代方法,比如方法重载,我可以创建两个方法,它们都调用printBinary,但是一个接受Long,另一个接受Integer.但是如果我想用一种方法做到这一点我怎么能实现呢?
public static <T extends Object> void print(T arg){
System.out.println(arg);
}
public static <T extends Number> void printBinary(T arg){
if(arg instanceof Long){
print(Long.toBinaryString(arg)); //this throws an error incompatible types: Number cannot be converted to long
}else{
print(Integer.toBinaryString(arg)); //this throws an error incompatible types: Number cannot be converted to int
}
}
解决方法:
说明
你的写作
public static <T extends Number> void printBinary(T arg)
所以你声明T是扩展Number的东西.非常重要的是,请注意,关于T,我们不能再了解它.所以你只能安全地假设它是数字而不是更多(没有检查,例如使用instanceof).
接下来就是你写的
// requires long
print(Long.toBinaryString(arg));
// requires int
print(Integer.toBinaryString(arg));
但是这两种方法都不需要Number,它们需要long和int.看看他们的文档(Long,Integer).
即使我们考虑装箱,Java也只能将Long转换为long,将Integer转换为int(反之亦然).但不是Number to Long或Number to Integer.数字不一定是长整数或整数.例如,它也可以是Double.你不知道T是什么,你只知道它至少是数字类型.
实用方法
所以你需要做的是显式地将arg转换为long和int.因此,您可以使用Number提供的实用程序方法,即Number#longValue和Number#intValue:
print(Long.toBinaryString(arg.longValue()));
print(Integer.toBinaryString(arg.intValue()));
在instanceof后施放
另一种可能是施放它们.正如您已经使用instanceof检查过,T确实是Long或Integer类型,您可以安全地转换它:
print(Long.toBinaryString((Long) arg));
print(Integer.toBinaryString((Integer) arg));
在转换后,Java会自动将Long转换为long,将Integer转换为int,这称为取消装箱.或者为了使其更明确,请自行调用取消装箱方法:
print(Long.toBinaryString(((Long) arg).longValue()));
print(Integer.toBinaryString(((Integer) arg).intValue()));
笔记
准确地说,使用当前代码取消选中对Integer的强制转换.你还需要检查arg instanceof Integer,因此更安全:
if (arg instanceof Long) {
// Cast to Long is safe
} else if (arg instanceof Integer) {
// Cast to Integer is safe
} else {
// Neither Long nor Integer, for example Double
throw new IllegalArgumentException("Only Long and Integer supported.");
}
内容总结
以上是互联网集市为您收集整理的java方法采用T extends Number全部内容,希望文章能够帮你解决java方法采用T extends Number所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。