views:

90

answers:

2
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);
    }
+3  A: 

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.

Jim Ferrans
+4  A: 

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.

skaffman