获取大于0的int时,Map TreeMap项会返回null吗?

Jun*_*ded 1 java collections map

    Score.clear();
    for (Client player : getPlayers()) {
        Client c = (Client) player;
        Score.put(c.gameScore, c);
    }

    Client WINNER = Score.get(Score.size() - 1);
    if (WINNER != null) {
        System.out.println("it works.");
    }
    else {
        System.out.println("its a null");
    }
Run Code Online (Sandbox Code Playgroud)

该怎么做:

遍历所有客户端,然后将客户端的分数对象添加到Map集合(treemap)中.然后找到得分最高的客户.

TreeMap集合从最低的int到最高的int,如下所示:( - 5,0,6,8,110,647).

我尝试了当前的代码,当客户有0分(全部)时,它工作正常并输出"它工作.".但是一旦我在其中一个客户中得到200分,就会说"它是空的".

为什么它最终成为空?

public static Map<Integer, Client> Score = new TreeMap<Integer, Client>();
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 5

这个:

Score.get(Score.size() - 1)
Run Code Online (Sandbox Code Playgroud)

不会得到地图的一个键,其值是最后一项,但价值Score.size() - 1,如果有的话.因此,它不起作用是正常的.

既然你使用了a TreeMap,那就意味着它也是一个SortedMap.因此你可以这样做:

// declare the map
final SortedMap<Integer, Client> scores = new TreeMap<>();

// fill the map

// get the last entry
scrores.get(scores.lastKey());
Run Code Online (Sandbox Code Playgroud)

请注意,您最好遵循Java约定:变量名称应以小写字母开头.

另一种选择是使用SortedSet自定义Comparator.