I recently came across an example where the author initializes a HashMap like shown below.
Map<Integer, List<Integer>> graph = new HashMap<>() {
{
put(0, Arrays.asList(1));
put(1, Arrays.asList(0, 2, 3));
put(2, Arrays.asList(1, 3));
put(3, Arrays.asList(1, 2));
}
};
From what I understand, the above code supplies an overridden anonymous object of the HashMap class.
I have been using the below way of creating and putting values in objects.
Map<Integer, List<Integer>> graph = new HashMap<>();
graph.put(0, Arrays.asList(1));
graph.put(1, Arrays.asList(0, 2, 3));
graph.put(2, Arrays.asList(1, 3));
graph.put(3, Arrays.asList(1, 2));
I agree that the author's way seems much clean and elegant, therefore, I am thinking of adopting it.
My question is apart from elegance, are there any other benefits to this? Are there any pitfalls/side-effects that I should be careful of?
Thank you.