Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Possible to Return Either Float or Integer?

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(".")));
}
like image 824
prog rice bowl Avatar asked Jan 28 '14 05:01

prog rice bowl


2 Answers

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
}
like image 101
Keerthivasan Avatar answered Nov 03 '22 00:11

Keerthivasan


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();
}
like image 34
Evgeniy Dorofeev Avatar answered Nov 03 '22 00:11

Evgeniy Dorofeev