So this is a very very basic question. I was reading though a class written by a colleague and I’ve only been doing Java for about six month and I cam across:
private Map<Dimension, Object> data = new HashMap<Dimension, Object>();
Of course, I consulted online but it didn’t really give an explanation I could understand too well. So I’m wondering if anyone can explain what this code is doing and what Maps do in general? What is a Map or HashMap (and why when a Map is declared are they creating a HashMap?). Also what are Maps used for and what makes them better than say an ArrayList?
From Oracle’s Map Interface tutorial:
So the contents of the Map in your code might be:
As to the difference between Maps and Arrays:
Maps store key/value pairs and provide accessors, e.g. to a value given a key.
ArrayList (and Lists in general) provide ordered storage of values.
Maps are great for caches, where you need to look something up based on a key; usually they’re not ordered, but LinkedHashMap retains insertion order like a List.
The Map declaration in your code sample is pretty common, and it demonstrates the practice of declaring Collections variables as the interface type, and the value as an implementation of that interface. As others have pointed out, the interface (e.g.
Map) defines the methods available to users, whereas the implementation (e.g.HashMap) implements logic to support the interface.This is considered good practice because it allows you to change the underlying implementation of (in this case) Map without changing the code that uses it.