11

What is the difference between those two. Why does the latter create a new serializable class?

new ArrayList<Clazz>() 

creates a new empty ArrayList

new ArrayList<Clazz>(){}

Eclipse shows: The serializable class does not declare a static final serialVersionUID field of type long

2 Answers 2

13

In the first example, you're creating an ArrayList instance. In the latter you're creating instance of an anonymous subclass of ArrayList. Usually you would override one or more methods in the subclass, otherwise there's not much point in creating such. As John Skeet points out, there is one hacky reason to create an anonymous subclass of a generic type, see his answer.

The Eclipse warns that, in order to adhere to the Serializable specifications (ArrayList is Serializable, so all its subclasses are too), you should define an unique serialVersionUID in the subclass from which the deserialization process can ensure that the class definition has not changed significantly since it was serialized (significantly == you yourself have decided that the new definition is incompatible with the old one, so you can express the fact by changing the serialVersionUID). If you're never going to serialize the list, then the warning doesn't matter.

Sign up to request clarification or add additional context in comments.

Comments

7

As Joonas says, in the second example you're creating an anonymous inner class. However, there is a reason to do this even when you're not overriding any methods etc: it allows you to determine the element type of the ArrayList at execution time - because the superclass of the anonymous inner class is ArrayList<Clazz> rather than just ArrayList.

This is how type literals work in Guice. It's a bit of an ugly hack, but it gets the job done...

2 Comments

How does it allow him to determine the element type at runtime?
@LouisRhys: If you call getClass() on the instance, it will give the anonymous class. If you then call getGenericSuperclass() that Type will have the appropriate information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.