Java Possible to Return Either Float or Integer?
function, integer, java, numbers
Solution
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();
}
Problem
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("."))); } ```