Why does double bracket initialization request a SerialVersionUID?

public static List<Long> abc = new ArrayList<Long>(){{ //Asks for SerialVersionUID abc.add(5L); abc.add(7L); }}; public static List<Long> abc = new ArrayList<Long>();//Does not need SerialVersionUID static{ abc.add(5L); abc.add(7L); } 
+2
source share
2 answers

In the second example, you create an instance of a class that already has a specific serialVersionUID (i.e. ArrayList ).

In the first example, you define an anonymous subclass of ArrayList , and your subclass must have its own serialVersionUID . It is not always obvious that dual-binding initialization actually defines an anonymous class.

+5
source

Because in the first example, you create an anonymous subclass of ArrayList through "dual-binding initialization", and ArrayList implements the Serializable interface. SerialVersionUID is used during deserialization, and it is good practice to provide one, although not necessarily. Your IDE is probably configured to notify you of these alerts.

In your second example, you are not creating an anonymous subclass of ArrayList, just create an instance and call its methods.

+3
source

All Articles