Map.Entry without type declaration

330 Views Asked by At

I am new to Java, but I need to quickly grasp some fundamentals to be able to work with some basic data structures.

Here's a small example I would like to understand better, namely the Map.Entry<Integer,String> part.

HashMap<Integer,String> my_hashmap = new HashMap<>();

 my_hashmap.put(20,"twenty");
 my_hashmap.put(30,"thirty");

 for (Map.Entry<Integer,String> m:my_hashmap.entrySet()) {
     System.out.println(m.getKey() + " " + m.getValue());
 }

It turns out that I can omit the <Integer, String> declaration and it makes no difference at all. Is that a bad practice? As far as I understand, under the hood, this is somehow interpreted as the Object type so there's no problem, but that doesn't benefit from using generics. Is my understanding correct? Thanks.

1

There are 1 best solutions below

0
Eran On BEST ANSWER

It is bad practice to use raw types.

In your example, since you are simply printing the key and value of each entry, the code passes compilation and works, since it uses the toString() method implemented by all classes in order to print them.

If, on the other hand, you want to print the length() of the value String instead of the actual String, you would write

System.out.println(m.getKey() + " " + m.getValue().getLength());

Now, this won't pass compilation if you changed

for (Map.Entry<Integer,String> m:my_hashmap.entrySet())

to

for (Map.Entry m:my_hashmap.entrySet())

since Object doesn't have a length() method.