0

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?


  • You don't need to construct the wrappers explicitly. Jus do addValue(val);. Autoboxing will handle the rest. - shmosel
  • 1) Why do you need to compare relative, i.e. less than / greater than? Why is equals() 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 type String against a new value of type Double? - Andreas
  • Agree with @shmosel, but if you prefer to be explicit, you should use valueOf(), rather than new, e.g. addValue(Integer.valueOf(val));, which is exactly what autoboxing does. - Andreas
  • I would like to compare, because I want to check which one is greater than or less than, rather than if they just equal each other. - Hans Landa
  • @HansLanda So how do you want to handle my second point? - Andreas

Linked


Related

Latest