Why does double brace initialization asks for 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 Serial开发者_Python百科VersionUID
static{
abc.add(5L);
abc.add(7L);
}
In the second example, you're instantiating a class that already has a defined serialVersionUID
(i.e. ArrayList
).
In the first example, you're defining an anonymous subclass of ArrayList
, and your subclass needs to have its own serialVersionUID
defined. It's not always obvious that double-brace initialization actually defines an anonymous class.
Because in your first example you're creating an anonymous subclass of ArrayList via "double-brace initialization", and ArrayList implements the Serializable interface. The SerialVersionUID is used in deserialization, and it's a good practice to provide one, though not strictly necessary. Your IDE is probably configured to report these warnings.
In your second example, you are not creating an anonymous subclass of ArrayList, just instantiating one and calling its methods.
精彩评论