简体   繁体   English

如果在hashmap.put中构造

[英]If construct in hashmap.put call

I have a variable of type Hashmap <String,Integer >. 我有一个Hashmap <String,Integer >类型的变量。

In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. 在这种情况下,根据标志变量的值,可能需要对Integer值进行一些操作。 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. 在Hashmapvariable.put调用中。

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. 但是我不能删除“)”-put方法调用的右括号。

I don't get this. 我不明白 What mistake am I doing? 我在做什么错?

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

Does the trick 绝招

Edit: On Java 5, I suppose you can also write 编辑:在Java 5,我想你也可以写

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

due to auto-boxing. 由于自动装箱。

You cannot place a statement in the method call. 您不能在方法调用中放置语句。

However, one option could be to make an method that returns a Integer such as: 但是,一种选择可能是使方法返回一个Integer例如:

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

This isn't scheme, so if statements don't evaluate to a value. 这不是方案,因此if语句不求值。 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. 正如其他人所说的那样,您将不得不使用“三分法”(该名称由于某种原因而使我现在逃脱了)或创建一个函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM