I'm new to Java and am looking at the forEach method in the Map.class in Java... here is an excerpt of that method:
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
//more code follows...
My question is... what is going on with K k; and V v;? The method goes on the use k and v as local variables so I'm guessing the K k; and V v; lines are assigning the arguments to local variables... but if that's true why doesn't this syntax need a type? Thank you in advance for the help.
I didn't try anything or expect anything... just want to better understand what this code is doing.
CodePudding user response:
Even understanding what are generics this code alone is not really clear.
Therefore you need to take a look at the top of the Map
interface declaration
public interface Map<K,V>
Read also:
CodePudding user response:
Map<K, V>
is a parameterised type, which means that it represents a whole family of different types, such as
Map<String, Integer>
- aMap
where the keys areString
s and the values areInteger
sMap<Integer, LocalDate>
- aMap
where the keys areInteger
s and the values areLocalDate
s
and so on. But there's a kind of sameness about all these types - they're all a Map
where the keys have some type and the values have some other type.
Now the processing inside the Map
is going to be much the same, regardless of the type of its keys or the type of its values. So none of the code inside Map.class
should specify what those types are. Instead, it uses K
to represent whatever type the keys will be, and V
to represent whatever type the values will be. These letters are called type parameters, and they are used in Map.class
as a way to refer to the types that will be used in the Map
.
For example, if you have a Map<String, Integer>
, then K
means String
and V
means Integer
. If you have a Map
with different key type and value type, then K
and V
will mean something else.
In the method that you've shown in your question, k
is a local variable of the type represented by K
and v
is a local variable of the type represented by V
. Again, if you have a Map<String, Integer>
, k
is effectively a String
variable, and v
is an Integer
variable. But these could actually be any types at all.
Where you've written //more code follows...
the code in question will just be pulling a key and value out of the Map
, pointing the variables k
and v
at them, and then applying the BiConsumer
called action
to them.