0

Can somehow please help me understand this:

If I initialize a HashMap inline as follows:

Map<String, Object> updates = new HashMap<String, Object>(){{
                put("some-key", "some-value";
            }};

and I attempt to call some REST service, with this instance, it is not serialized correctly and service end point receives null.

If, however, I initialize the HashMap using regular mechanism:

 Map<String, Object> updates = new HashMap<>();
updates.put("some-key", "some-value");

This works just fine. Values come across. Anyone seen this?

Klaus Nji
  • 18,107
  • 29
  • 105
  • 185
  • 1
    Without much looking, suspect [this](https://stackoverflow.com/questions/17804704/notserializableexception-on-anonymous-class) dupe. – Mena Dec 12 '18 at 16:36
  • 1
    Don't use the first way. It's a nasty hack. – khelwood Dec 12 '18 at 16:37
  • The nested class implicitly contains a reference to your outer class which is probably not Serializable. – Peter Lawrey Dec 12 '18 at 19:02
  • Guess have been spoiled by C#'s collection initializers. Wish Java has something similar to make this language less verbose. – Klaus Nji Dec 12 '18 at 19:50

0 Answers0