简体   繁体   English

ArrayList <>()和ArrayList <>(){}之间的区别

[英]Difference between ArrayList<>() and ArrayList<>(){}

What is the difference between those two. 两者之间有什么区别。 Why does the latter create a new serializable class? 后者为什么创建一个新的可序列化类?

new ArrayList<Clazz>() 

creates a new empty ArrayList 创建一个新的空ArrayList

new ArrayList<Clazz>(){}

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

In the first example, you're creating an ArrayList instance. 在第一个示例中,您将创建一个ArrayList实例。 In the latter you're creating instance of an anonymous subclass of ArrayList . 在后者中,您将创建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 . 正如John Skeet所指出的那样,创建一个泛型类型的匿名子类有一个不充分的理由,请参见他的回答

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 ). Eclipse警告说,为了遵守Serializable规范( ArrayListSerializable ,因此它的所有子类也是如此),您应该在子类中定义一个唯一的serialVersionUID ,反序列化过程可以确保该子类的反序列化过程可以确保类定义没有明显改变由于已将其序列化(很明显==,您自己已决定新定义与旧定义不兼容,因此您可以通过更改serialVersionUID来表达这一事实)。 If you're never going to serialize the list, then the warning doesn't matter. 如果您永远不会序列化列表,则警告无关紧要。

As Joonas says, in the second example you're creating an anonymous inner class. 正如Joonas所说,在第二个示例中,您正在创建一个匿名内部类。 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 . 然而,还有一个原因 ,即使你不覆盖任何方法等,以做到这一点:它可以让你确定的元素类型ArrayList在执行时-因为匿名内部类的超类ArrayList<Clazz> ,而不是只是ArrayList

This is how type literals work in Guice. 这就是类型文字在Guice中的工作方式。 It's a bit of an ugly hack, but it gets the job done... 这有点丑陋,但是可以完成工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM