0

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.

Sujal Mandal
  • 975
  • 1
  • 14
  • 29
  • 4
    Before you do that, think of `Map.of(0, List.of(1), 1, List.of(0, 2, 3), ...)`. That initialization hack is [generally frowned upon](https://stackoverflow.com/a/1958961/5761558). – ernest_k Apr 03 '22 at 06:10
  • @ernest_k thanks! you saved me some pain around json serialization. – Sujal Mandal Apr 04 '22 at 06:08

0 Answers0