I'm looking at a java hangman game here: https://github.com/leleah/EvilHangman/blob/master/EvilHangman.java
The code in particular is this:
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;
}
}
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 advance!
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).
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.
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;
}
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.