What's the harm in using Anonymous class?

后端 未结 6 1041
-上瘾入骨i
-上瘾入骨i 2021-01-31 08:41

The question arose while reading a answer to this question - How do I join two lists in java. This answer gave the solution

List newList = new Arra         


        
6条回答
  •  野的像风
    2021-01-31 09:00

    The "ugly" and "do not use in production" comments refer to this specific use of anonymous classes, not to anonymous classes in general.

    This specific use assigns newList an anonymous subclass of ArrayList, an entirely new class created with a single purpose in mind - namely, initializing a list with the content of two specific lists. This is not very readable (even an experienced reader would spend a few seconds figuring it out), but more importantly, it can be achieved without subclassing in the same number of operations.

    Essentially, the solution pays for a small convenience with creating a new subclass, which may result in problems down the road, for example, in situations when you try to persist this collection using an automated framework that expects collections to have specific types.

提交回复
热议问题