下面的代碼不起作用:的Java:Genrics - 兩個類似的代碼,一個不工作
class Stats<T extends Number>
{
T[] nums;
Stats(T[] o)
{
nums = o;
}
double average()
{
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum/nums.length;
}
boolean sameAvg(Stats<T> ob)
{
if(average() == ob.average())
return true;
return false;
}
}
class BoundsDemo
{
public static void main(String args[])
{
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
if(iob.sameAvg(dob))
System.out.println("Averages are the same.");
else
System.out.println("Averages differ.");
}
}
但是,以下工作:
class Gen04<T extends Number>
{
T num;
void set(T a)
{
num = a;
}
T get()
{
return num;
}
boolean equals(Gen04<T> ob)
{
if(num.doubleValue() == ob.get().doubleValue())
return true;
else
return false;
}
}
class GenericCompare
{
public static void main(String args[])
{
Gen04<Integer> obI1 = new Gen04<Integer>();
obI1.set(new Integer(5));
Gen04<Double> obI2 = new Gen04<Double>();
obI2.set(new Double(5.0));
System.out.println("obI1 and obI2 are equal = "+obI1.equals(obI2));
}
}
的區別是什麼?在這兩個方案,我想打電話從參數類型調用對象
你能解釋一下「不起作用嗎?」你會得到什麼錯誤? – markspace
您是否收到任何錯誤或錯誤的答案? – SMA
錯誤:不兼容類型:統計不能轉換爲統計 –