3 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個贊
另一個答案行不通,但如果我們稍微修改一下,它就可以工作:
public Number add(Number i, Number j) {
if(i instanceof Integer && j instanceof Integer) {
return i.intValue() + j.intValue();
} else if(i instanceof Double && j instanceof Double) {
return i.doubleValue() + j.doubleValue();
} //you can check for more number subclasses
return null; //or throw and exception
}
但這比超載要丑陋得多。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個贊
您可以采用通用方法,而不是重載。
public static class Utils {
public static <T extends Number> Number multiply(T x, T y) {
if (x instanceof Integer) {
return ((Integer) x).intValue() + ((Integer) y).intValue();
} else if (x instanceof Double) {
return ((Double) x).doubleValue() + ((Double) y).doubleValue();
}
return 0;
}
}
并像這樣使用它
Utils.<Double>multiply(1.2, 2.4); // allowed
Utils.<Integer>multiply(1.2, 2.4); // not allowed
Utils.<Integer>multiply(1, 2); // allowed

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個贊
當(dāng)然有可能。首先,double 函數(shù)可以接受 int 值,因此如果需要,您可以將其用于兩者。但是,如果您仍然想實(shí)現(xiàn)目標(biāo),最好的方法是使用泛型。另一種方法是讓您的方法接受兩個類的父類(例如 Object),然后進(jìn)行適當(dāng)?shù)霓D(zhuǎn)換,如下所示:
public class Add {
enum ParamType {
INT,
DOUBLE
}
public static Object add(Object i, Object j, ParamType paramType) {
if (paramType.equals(ParamType.INT)) {
return (int) i + (int) j;
} else {
return (double) i + (double) j;
}
}
public static void main(String[] args) {
System.out.println(add(3.4, 5.2, ParamType.DOUBLE));
System.out.println(add(3, 5, ParamType.INT));
}
}
添加回答
舉報(bào)