6

I use the Apache Commons package extensively, especially the StringUtils, BooleanUtils, ObjectUtils, MapUtils classes and find them extremely helpful. I am wondering if there are classes such as IntegerUtils, DoubleUtils that provide a similar functionality for their respective wrapper classes (I do not find such classes in the Apache Commons package).

Thanks,

Venkat

centic
  • 15,565
  • 9
  • 68
  • 125
Venk K
  • 1,157
  • 5
  • 14
  • 25
  • What would you expect to be there? – Louis Wasserman Mar 28 '13 at 22:06
  • 8
    You're looking for `org.apache.commons.lang.NumberUtils`. – Luiggi Mendoza Mar 28 '13 at 22:07
  • @LouisWasserman: Some methods such as equals that are null-safe much like the methods we have for StringUtils. – Venk K Mar 28 '13 at 23:32
  • @LuiggiMendoza: Thank you Luiggi for your suggestion. I believe you are refering to org.apache.commons.lang3.math.NumberUtils. I did look it up but did not find null-safe methods taking two or more Integer or Double objects. – Venk K Mar 28 '13 at 23:38
  • Null-safe equality isn't different for `Integer` or `String`: do they have one for `Object`s in general? (Assuming, of course, you consider allowing nulls to be a good thing.) – Louis Wasserman Mar 28 '13 at 23:57
  • @LouisWasserman: Apache Commons has ObjectUtils. As you said, ObjectUtils.equals should work for Integer and Double. For Strings, I do not know why they had a separate method called equals. I looked up at the source code and it is very similar to what ObjectUtils.equals does. Thanks for your comments. – Venk K Mar 29 '13 at 01:01
  • For future visitors' convenience here's a link to [NumberUtils](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html). It contains methods like `toDouble(String str, double defaultValue)` Convert a String to a double, returning a default value if the conversion fails. – qben Apr 13 '15 at 09:08

1 Answers1

6

I wish they had a utilities class for numbers as useful as the one for strings. NumberUtils class is all about converting numbers to/from strings.

You can use ObjectUtils to do null-safe Integer operations though.

Instead of:

foo(Integer arg) {
  if(arg != null && arg == 1)
    doSomething();
}

You can do:

foo(Integer arg) {
  if(ObjectUtils.defaultIfNull(arg, 0) == 1)
    doSomething();
}

In the case where the Integer you are comparing is, say, a function call that returns an Integer, this will allow you to only call the function once without creating a throwaway variable.

Kip
  • 107,154
  • 87
  • 232
  • 265