【发布时间】:2015-08-21 08:04:19
【问题描述】:
public class ClassGenericParameterized<T> {
public void add(T t1, T t2){
//System.out.println(t1+t2);
System.out.println(Integer.parseInt(t1.toString()) + Integer.parseInt(t2.toString()));
}
public void multiply(T t1, T t2){
System.out.println(Integer.parseInt(t1.toString()) * Integer.parseInt(t2.toString()));
}
public void subtract(T t1, T t2){
System.out.println(Integer.parseInt(t1.toString()) - Integer.parseInt(t2.toString()));
}
public void division(T t1, T t2){
System.out.println(Integer.parseInt(t1.toString()) / Integer.parseInt(t2.toString()));
}
public static void main(String[] args) {
ClassGenericParameterized<Integer> ob = new ClassGenericParameterized<Integer>();
ob.add(1,2);
ob.multiply(2, 4);
ob.subtract(15, 6);
ob.division(6, 3);
}
}
java中生成类Generic的逻辑和需要是什么
当替换语句时
ClassGenericParameterized<Integer> ob = new ClassGenericParameterized<Integer>()
通过
ClassGenericParameterized<Double> ob = new ClassGenericParameterized<Double>()
给予
Error(The method add(Double, Double) in the type ClassGenericParameterized<Double> is not applicable for the arguments (int, int))
我认为这是因为在 add 方法中写的语句为 Integer.parseInt(t1.toString()) + Integer.parseInt(t2.toString())
所以再次尝试替换语句
System.out.println(Integer.parseInt(t1.toString()) + Integer.parseInt(t2.toString()));
通过
System.out.println(t1+t2)
给了
Error(The operator + is undefined for the argument type(s) T, T).
那么这怎么能成为真正意义上的通用呢?有人可以解释一下为什么会发生这种情况以及如何纠正这个错误来实现我的功能吗?
【问题讨论】:
-
问题是
int不能自动装箱到Double。 -
而且您完全误解了泛型,因为
T的实际类型在您的方法中没有任何意义。 -
是的,我已经猜到了,有什么方法可以纠正它? @sotirios
-
自动装箱在你的情况下不起作用,试试这个:
ob.add((double)1,(double)2); -
你想做什么?没有 generic 方法可以像那样做 add()。
标签: java collections