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;
...
}
and
public boolean equals(Object ob) {
if (ob.getClass() != getClass()) return false;
...
}
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)
).
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.
It is something to be aware of however.
What I would suggest is to do it slightly differently:
List<String> list = new ArrayList<String>(
Arrays.asList("hello", "goodbye")
);
Sure it's more wordy but you're less likely to get in trouble this way as the resultant class is a "pure" ArrayList
.