繁体   English   中英

遍历哈希图?

[英]Iterate through a hashmap?

我试图在Java中取得高分。 基本上,我希望哈希表保存双精度值(因此索引从最高双精度值开始,因此我更容易对高分进行排序),然后第二个值将是客户端对象,如下所示:

private HashMap<Double, TempClient> players = new HashMap<Double, TempClient>();

并插入一个新值:

        TempClient client = new TempClient(kills, rank, deaths, name);
        this.players.put(client.getKdr(), client);

现在,我当然不能遍历哈希表,因为它是通过键而不是索引来获取列表项的。

如何遍历哈希图? 或对我的情况有什么好主意?

我在Foo课堂上尝试过:

输出:

0.5
0.6
0.9
0.1
2.5

码:

public class Foo {

    public static void main(String[] args) {
        HashMap<Double, String> map = new LinkedHashMap<Double, String>();
        map.put(0.5, "hey");
        map.put(0.6, "hey1");
        map.put(0.9, "hey2");
        map.put(0.1, "hey425");
        map.put(2.5, "hey36");
        for (Double lol : map.keySet()) {
            System.out.println(lol);
        }
    }

}

您可以像这样迭代。

for (Double k : players.keySet())
{
    TempClient p = players.get(k);
    // do work with k and p
}

如果要保持键排序,请使用例如TreeMap。
如果要按插入顺序保留键
他们在那里,使用例如LinkedHashMap。

最好的方法是使用EntrySet遍历hashmap。

for (Map.Entry<Double, TempClient> entry : map.entrySet()) {
    Double  key= entry.getKey();
    TempClient value= entry.getValue();
    // ...
}

您最好使您的TempClient对象实现Comparable,将它们添加到列表中,然后仅使用Collections.sort()。

由于您无法对HashMap项目进行排序,也无法按TreeMap的值对它们进行排序,因此可以将TreeSet与自定义类一起使用:

class Score implements Comparable<Score>
{
  final Player player;
  final int score;

  Score(Player player, int score) {
    this.player = player;
    this.score = score;
  }

  public int compareTo(Score other) {
    return Integer.compare(this.score, other.score);
  }

  public int hashCode() { return player.hashCode(); }
  public boolean equals(Object o) { return this.player.equals(...); }
}

TreeSet<Score> scores = new TreeSet<Score>();
score.add(new Score(player, 500));

for (Score s : scores) {
  ..
}

这将具有两个优点:

  • 这将是迭代的
  • 它将分数自动排序

它应该可以轻松地与equalshashCodecompareTo之间的一致性保持一致,但是也许您应该进行一些调整(因为它是未经测试的代码)。

暂无
暂无

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

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