If you construct in hashmap.put call

I have a variable of type Hashmap <String,Integer

>.

In this, the Integer value may be required for some manipulation depending on the value of the 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 am getting the error:

Syntax error on tokens (s), inappropriate construction.

in the call to Hashmapvariable.put.

I also get another error

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

in the final "); line. But I can't remove the") "- its the closing parentheses to call the put method.

I do not understand. What mistake am I making?

0


source to share


3 answers


You cannot put a statement in a method call.

However, one option would be to create a method that returns Integer

, for example:

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));

      

+4


source


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

      

Is there a trick

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



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

      

due to automatic boxing.

+7


source


It is not a schema, so if the statements do not evaluate the value. You will need to use tri-if-thing (the name is escaping me for some reason right now) or create a function as someone else said.

0


source







All Articles