This question already has an answer here:
I have a situation where I have several functions that get passed in different types (float, int, double, etc). Currently I am boxing these types into Float, Integer, Double, etc, and passing them into one function which takes an Object parameter. Similar to the following:
private void handleInt(int val) {
//do something
addValue(new Integer(val));
}
private void handleFloat(float val) {
//do something
addValue(new Float(val));
}
private void handleDouble(double val) {
//do something
addValue(new Double(val));
}
private void addValue(Object val) {
//Do something with object val
//.compareTo needs to be called here to compare previous value
}
I would like to compare the val parameter sent to addValue with a previous one I store in an array. However, because Object is a base class of all of the different boxed types (Float, Integer, etc), do I need to write my own class that extends Object and implements comparable?
And in my compareTo function, how would I accomplish this?
addValue(val);
. Autoboxing will handle the rest. - shmoselequals()
not enough? All objects implement equals, and can compare disparate types. --- 2) If you must compare relative, when how to you compare a previous value of typeString
against a new value of typeDouble
? - AndreasvalueOf()
, rather thannew
, e.g.addValue(Integer.valueOf(val));
, which is exactly what autoboxing does. - Andreas