我无法理解T是如何使用Integer和String的.在显示函数中,T处理Integer和String.这段代码是如何工作的?
class firstBase {
<T> void display(T give_num, T give_String) {
System.out.println("The given number is = "
+ give_num + " The given String is = " + give_String);
System.out.println("The class of given number is = "
+ give_num.getClass() +
" The class of given_String is = "+give_String.getClass());
}
}
public class testanonymous {
public static void main(String[] args) {
firstBase fb = new firstBase();
fb.display(100, "xyz");
}
}
Run Code Online (Sandbox Code Playgroud)
你正在调用方法的原始形式,它基本上等于
void display(Object give_num, Object give_String)
Run Code Online (Sandbox Code Playgroud)
在这里,你提供的两个参数都适合,因为100是自动装箱到Integer(它是子类Object),而"xyz"是String(它是一个子类Object)
要正确使用泛型,您必须:
fb.<String>display(100, "xyz");
Run Code Online (Sandbox Code Playgroud)
要么
fb.<Integer>display(100, "xyz");
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,您都会注意到代码无法编译,因为编译器会知道您在运行时T用Integer/ 替换的意图String,但参数类型与提供的类型不同.
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |