麻烦了解Java Map Entry集 [英] Trouble understanding Java map Entry sets

查看:108
本文介绍了麻烦了解Java Map Entry集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个java hangman游戏: https:// github .com / leleah / EvilHangman / blob / master / EvilHangman.java

I'm looking at a java hangman game here: https://github.com/leleah/EvilHangman/blob/master/EvilHangman.java

代码特别是这样的:

Iterator<Entry<List<Integer>, Set<String>>> k = partitions.entrySet().iterator();
while (k.hasNext())
{
    Entry<?, ?> pair = (Entry<?, ?>)k.next();
    int sizeOfSet = ((Set<String>)pair.getValue()).size();
    if (sizeOfSet > biggestPartitionSize)
    {
        biggestPartitionSize = sizeOfSet;
    }
}

现在我的问题。我的谷歌foo是弱的我猜,我找不到很多条目集以外的java文档本身。是只是地图的临时副本吗?我无法找到任何有关语法的信息:

Now my question. My google foo is weak I guess, I cannot find much on Entry sets other than the java doc itself. Is is just a temporary copy of the map? And I cannot find any info at all on the syntax:

Entry<?, ?>

任何人都可以解释或指出我对这些问号发生了什么?
感谢高级。

Can anyone explain or point me toward an explanation of what is going on with those question marks? Thanks in advanced.

推荐答案

entrySet 是Map中所有Entries的集合,即Map中所有键值对的集合。因为地图由键值组成,如果要迭代,则需要指定是否要遍历键,值或两者(Entries)。

An entrySet is the set of all Entries in a Map - i.e. the set of all key,value pairs in the Map. Because a Map consists of key,value pairs, if you want to iterate over it you need to specify whether you want to iterate over the keys, the values, or both (Entries).

<?,?> 表示变量保存一个Entry,该值可以是任何类型。这通常表明我们不在乎它所持有的什么类型的价值观。在你的代码中并不是这样,因为你需要将值转换为 Set< String> ,以便检查它的大小。

The <?,?> indicates that the pair variable holds an Entry where the key and the value could be of any type. This would normally indicate that we don't care what types of values it holds. In your code this is not the case, because you need to cast the value to Set<String> so you can check its size.

您还可以按如下方式重写代码,避免转换为 Set< String>

You could also rewrite the code as follows, avoiding the cast to Set<String>

Iterator<Entry<List<Integer>, Set<String>>> k = partitions.entrySet().iterator();
while (k.hasNext())
{
Entry<?, Set<String>> pair = (Entry<?, Set<String>>)k.next();
int sizeOfSet = pair.getValue().size();
if (sizeOfSet > biggestPartitionSize)
{
     biggestPartitionSize = sizeOfSet;
}

当我们需要更具体地了解条目所持有的类型时,可以使用完整的类型: Entry< List< Integer>,Set< String>> 。这避免了将密钥或值转换为特定类型(以及投射到错误类型的风险)的需要。

When we need to be more specific about the types that the Entry holds, we can use the full type: Entry<List<Integer>, Set<String>>. This avoids the need to cast the key or value to a particular type (and the risk of casting to the wrong type).

您还可以仅指定类型键或值,如上例所示。

You can also specify just the type of the key, or the value, as shown in my example above.

这篇关于麻烦了解Java Map Entry集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆