If construct in hashmap.put call

I have a variable of type Hashmap<String,Integer>.

In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...

Hashmapvariable.put( somestring,
    if (flag_variable) {
     //manipulation code goes here
     new Integer(manipulated value);
    } else {
     new Integer(non-manipulated value);
    }
);

But I get an error:

Syntax error on token(s), misplaced constructs.

at the Hashmapvariable.put call.

I also get another error

Syntax error on token ")", delete this token.

at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.

I don't get this. What mistake am I doing?

Answers


You cannot place a statement in the method call.

However, one option could be to make an method that returns a Integer such as:

private Integer getIntegerDependingOnFlag(boolean flag)
{
    if (flag)
        return new Integer(MANIPULATED_VALUE);
    else
        return new Integer(NON-MANIPULATED_VALUE);
}

Then, you can make a call like this:

hashmap.put(someString, getIntegerDependingOnFlag(flag));

 new Integer(flag_variable ? manipulated value : non-manipulated value)

Does the trick

Edit: On Java 5, I suppose you can also write

hashmap.put(someString, flag_variable ? manipulated value : non-manipulated value)

due to auto-boxing.


This isn't scheme, so if statements don't evaluate to a value. You'll have to use a tri-if-thing (the name escapes me for some reason right now) or create a function, as someone else said.


Need Your Help

CruiseControl.rb: running cruise rake task with current revision as parameter

rake capistrano cruisecontrol.rb

when CruiseControl.rb wants to perform an integration test it looks for a rake task called "cruise" within the project and executes it.

navigate to previous fragment on click on back button:

android android-fragments fragment

I have two fragment in my activity fragment1 and fragment2, i want when user click on back button from fragment2 it should navigate user to fragement1