Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean.parseBoolean("1") = false...?

Tags:

java

sorry to be a pain... I have: HashMap<String, String> o

o.get('uses_votes'); // "1"

Yet...

Boolean.parseBoolean(o.get('uses_votes')); // "false"

I'm guessing that ....parseBoolean doesn't accept the standard 0 = false 1 = true?

Am I doing something wrong or will I have to wrap my code in:

boolean uses_votes = false;
if(o.get('uses_votes').equals("1")) {
    uses_votes = true;
}

Thanks

like image 454
Thomas Clayson Avatar asked Oct 12 '11 01:10

Thomas Clayson


3 Answers

It accepts only a string value of "true" to represent boolean true. Best what you can do is

boolean uses_votes = "1".equals(o.get("uses_votes"));

Or if the Map actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.

like image 123
BalusC Avatar answered Oct 16 '22 16:10

BalusC


I have a small utility function to convert all possible values into Boolean.

private boolean convertToBoolean(String value) {
    boolean returnValue = false;
    if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || 
        "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value))
        returnValue = true;
    return returnValue;
}
like image 30
Saqib Avatar answered Oct 16 '22 16:10

Saqib


According to the documentation (emphasis mine):

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

like image 14
mellamokb Avatar answered Oct 16 '22 18:10

mellamokb