为了添加实例初始化块而创建的匿名类的意外后果 [英] Unintended consequences of anonymous class created just for sake of adding instance initialization block

查看:137
本文介绍了为了添加实例初始化块而创建的匿名类的意外后果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于Java代码的问题,例如:

This is a question about Java code such as:

List<String> list = new ArrayList<String>() {{add("hello"); add("goodbye");}}

程序员匿名扩展ArrayList只是为了在实例初始化块中推..

where the programmer has extended ArrayList anonymously just for the sake of shoving in an instance initialization block.

问题是:如果程序员的唯一目的只是达到以下目的:

The question is: if the sole intention of the programmer is merely to achieve the same as:

List<String> list = new ArrayList<String>();
list.add("hello");
list.add("goodbye");    

然后第一种方式会产生什么样的意外后果?

then what are the unintended consequences of doing it the first way?

推荐答案

执行这类代码(在一般情况下)的危险在于你可能会破坏 equals()方法。这是因为有两个通用模板:equals()

The danger of doing that sort of code (in the general case) is that you might break equals() methods. That's because there are two general templates for equals():

public boolean equals(Object ob) {
  if (!(ob instanceof MyClass)) return false;
  ...
}

public boolean equals(Object ob) {
  if (ob.getClass() != getClass()) return false;
  ...
}

第一个仍然适用于匿名子类你在谈论但第二个不会。事实上,第二个被认为是最佳实践,因为instanceof不一定是可交换的(意味着 a.equals(b)可能不等于 b.equals(a))。

The first will still work with the anonymous subclasses you're talking about but the second won't. Thing is, the second is considered best practice because instanceof isn't necessarily commutative (meaning a.equals(b) might not equal b.equals(a)).

特别是在这种情况下, ArrayList 使用 AbstractList.equals()方法,该方法只检查另一个对象是 instanceof 接口列出,所以你没事。

Specifically in this case however ArrayList uses the AbstractList.equals() method which merely checks that the other object is an instanceof the interface List, so you're fine.

但是要注意这一点。

我建议的做法略有不同:

What I would suggest is to do it slightly differently:

List<String> list = new ArrayList<String>(
    Arrays.asList("hello", "goodbye")
);

当然它更加冗长,但你不太可能以这种方式遇到麻烦,因为结果类是一个纯 ArrayList

Sure it's more wordy but you're less likely to get in trouble this way as the resultant class is a "pure" ArrayList.

这篇关于为了添加实例初始化块而创建的匿名类的意外后果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆