繁体   English   中英

三元运算符错误

[英]An error with a ternary operator

在下面的代码中:

public Map<Integer, Integer> leavesCount = new HashMap<Integer, Integer>();

public void addLeaf(int leaf, int count){
    leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);
}

我在containsKey内的leaf出现以下错误:

Type mismatch: cannot convert from int to boolean

有谁知道如何解决这个问题?

重写为

leavesCount.put(leaf, leavesCount.containsKey(leaf) ? (leavesCount.get(leaf) + count) : count)

这不是三元运算的工作方式。 要使用三元函数,您需要将函数更改为

public void addLeaf(int leaf, int count){
    leavesCount.put( leaf, leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count)
}

这并不是真正的最佳实践。 您最好使用if语句。

public void addLeaf(int leaf, int count){
    if(leavesCount.containsKey(leaf)){
        leavesCount.put(leaf, leavesCount.get(leaf) + count);
    }else{
        leavesCount.put(leaf, count);
    }
}

这样做的原因是可读性。 将三元数放入函数调用中可能会开始变得混乱。

您也可以将其移至var。

public void addLeaf(int leaf, int count){
    count = leavesCount.containsKey(leaf) ? leavesCount.get(leaf) + count : count;
    leavesCount.put( leaf, count)
}

在Java 8中,有一个优雅的内置方法可以执行您想要的操作:

public Map<Integer, Integer> leavesCount = new HashMap<>();

public void addLeaf(int leaf, int count) {
    leavesCount.merge(leaf, count, Integer::sum);
}

它使用Map.merge方法(该方法需要键和值)以及合并功能(如果键已存在于地图中)将旧值与新值合并在一起的合并函数

对于合并功能,我正在使用Integer::sum ,这是对Integer.sum方法的方法引用。 该方法引用的行为类似于BiFunction<Integer, Integer, Integer> ,即,它期望两个值并返回它们的和。

您应该替换leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count); leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, count);

    if (leavesCount.containsKey(leaf)) {
        leavesCount.put(leaf, leavesCount.get(leaf) + count);
    } else {
        leavesCount.put(leaf, count);
    }

暂无
暂无

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

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