3

我有课,比如说曲棍球。曲棍球类将设置曲棍球的分数,如下面的代码:

public class Hockey{
  private HashMap<String, Integer> hockeyScore;

  public Hockey(){
    hockeyScore = new HashMap<String, Integer>();
  }

  public void setHockeyScore(String clubName, int score){
    hockeyScore.put(clubName, score);  
  }
}

一场曲棍球比赛只有两支球队和两个分数,可以交换分数吗?例如,当我们插入 hashmap 时,它会带有键和值......

团队'a' = 23

团队'b' = 10

然后你交换哈希图中的值,看起来像......

团队'a' = 10

团队'b' = 23

抱歉,我想知道是否有一种类似的方法可以交换分数,而无需手动使用“a”和“b”参考。就像一旦您将任何键和值插入哈希图中,此方法将交换值。

4

5 回答 5

6

当然,您传统上交换值的方式:

Integer tmp = map.get(a);
map.put(a, map.get(b));
map.put(b, tmp);
于 2012-11-21T23:33:47.587 回答
1

您可以使用此单线交换Map条目:

hockeyScore.put(a, hockeyScore.put(b, hockeyScore.get(a)));
于 2012-11-21T23:37:09.340 回答
0

I am having trouble imagining why you would want to do this, but it is only possible in the case of a Map with 2 entries--otherwise, swap is meaningless.

My Java is a bit rusty, and I am not going to pull out Eclipse just to check syntax but something quite similar to this should do the job for you:

Map<string, int> swapped(string key1, string key2, Map<string, int> m) {
    Map dummy = new HashMap<string, int>();

    dummy.put(key2, m.get(key1));
    dummy.put(key1, m.get(key2));

    return dummy;
}

If you are more ambitious, you could iterate the entries to get the keys rather than having to have them available.

于 2012-11-21T23:38:24.500 回答
0
Integer aScore = hockeyScore.get("a");
hockeyScore.put("a", map.get("b"));
hockeyScore.put("b", aScore);

and the threadsafe variant

synchronized (hockeyScore) {
   Integer aScore = hockeyScore.get("a");
   hockeyScore.put("a", map.get("b"));
   hockeyScore.put("b", aScore);
}
于 2012-11-21T23:46:36.043 回答
0

Thank you very much for your help!

I have figured out away to swap the values in the hashmap. First I collected the scores and put them into an arraylist and then i compared the arraylist to the hashmap and re set the hash map according the the arraylist.

public void swapScores(){ 
        for(Map.Entry<Team, Integer> getScores: winningTeam.entrySet()){
            if(scores.get(0).equals(getScores.getValue())){
                getScores.setValue(scores.get(1));
                System.out.println(getScores.getKey().getTeamName()+":"+getScores.getValue());
            }else if(scores.get(1).equals(getScores.getValue())){
                getScores.setValue(scores.get(0));
                System.out.println(getScores.getKey().getTeamName()+":"+getScores.getValue());
            }
        }

    }

If there is a shorter way to do this please let me know.

Thank you again everyone!

于 2012-11-22T01:28:18.743 回答