Is it possible to have a function that returns either Integer or Float? I want to have the 2 functions become one if it's possible:
private static Integer parseStringFormatInt(String val){
System.out.println(Integer.parseInt(val.substring(0, val.indexOf("."))));
return Integer.parseInt(val.substring(0, val.indexOf(".")));
}
private static Float parseStringFormatFloat(String val){
System.out.println(Float.parseFloat(val.substring(0, val.indexOf("."))));
return Float.parseFloat(val.substring(0, val.indexOf(".")));
}
Make the return type as Number
since both Float
and Integer
are subtypes of Number
like below
private static Number parseStringFormatNumber(String val){
//Based on your conditions return either Float or Integer values
}
You can also make instanceof
operator to do the test on the return value, to get the exact type of the returned value. i.e Float
or Integer
if(returnedValue instanceof Float)
{
// type cast the returned Float value and make use of it
}
else if(returnedValue instanceof Integer)
{
// type cast the returned Integer value and make use of it
}
You can use Number as return type, or make the method generic
static <T extends Number> T parseString(String str, Class<T> cls) {
if (cls == Float.class) {
return (T) Float.valueOf(str);
} else if (cls == Integer.class) {
return (T) Integer.valueOf(str);
}
throw new IllegalArgumentException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With