Java Java Data Structures Efficiency! Design the UI

Map.Entry<String, String>

So what is the difference between these two, i tried both and both of them works flawlessly

Map<String, String> mMenu = new HashMap<String, String>();
mMenu.put("add", "add a new song to the song book");
mMenu.put("quit", "Give up. Exit the program...");

for (Map.Entry<String, String> option : mMenu.entryset()) {
      System.out.printf("%s-%s \n", option.getKey(), option.getValue());
}
Map<String, String> mMenu = new HashMap<String, String>();
mMenu.put("add", "add a new song to the song book");
mMenu.put("quit", "Give up. Exit the program...");

for (Map.Entry option : mMenu.entryset()) {
      System.out.printf("%s-%s \n", option.getKey(), option.getValue());
}

1 Answer

Lukas Dahlberg
Lukas Dahlberg
52,834 Points

The second example does not use what are called generics. So while it will work just fine, it's usually not a good idea in the real world because you don't get the benefits that come from the compiler's type-checking. The generics also allow you to avoid casting when you get an object from the map.

So it's better to use the former example with a firm declaration of what's in the Map. (In fact, the second version is what people had to do before Java 1.5 was released, so it's fairly outdated code.)

System.out.println("Sounds Legit. Thanks for the Answer :) ");