2017-07-19 146 views
-1

在下面的代碼中的錯誤:與三元運營商

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

我得到leafcontainsKey內出現以下錯誤:

Type mismatch: cannot convert from int to boolean 

有誰知道如何解決這個問題?

+0

您沒有將結果分配給任何東西。 – OldProgrammer

+1

您必須使用'if'語句,三元運算符僅用作表達式。 – Clashsoft

+1

你確定你在這段代碼中遇到這個錯誤嗎?你的代碼應該產生不同的錯誤。 – talex

回答

1

它改寫爲

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

你應該

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

這就是操作沒怎麼三元工作更換leavesCount.containsKey(leaf) ? leavesCount.put(leaf, leavesCount.get(leaf) + count) : leavesCount.put(leaf, 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) 
} 
+0

第二個建議讓你獲得了我的最高票數。這不是使用三元運算符的地方。 –

1

在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>,即它期待兩個值並返回它們的總和。