I was wondering why when I use an anonymous instanciation along with an instance initializer block, I get a “serializable class does not declare a static final serialVersionUID field of type long” compile-time warning.
Here’s what I mean. Let’s say I want to instantiate an ArrayList and at the same time add something to it like so:
ArrayList<Object> arrayList = new ArrayList<Object>(){{add(new Object());}};
If I compile this all is ok but I get the serialVersionUID field missing warning. Now ArrayList already implements serializable and has a private static final long serialVersionUID so why is it that when I use it like that it seems that that field “dissapears” and I get a warning for not having it declared?
When you create your anonymous class, you are actually extending
ArrayListand therefore, inheriting theSerializableinterface.All
Serializableclasses are supposed to have aserialVersionUIDso that you can distinguish between different serialized versions of the classes. Since the anonymous type is a new class, it would be a good idea to give it an ID so you can distinguish between different versions of it.