The danger of executing such code (in the general case) is that you may violate the equals() methods. This is because there are two common patterns 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 are talking about, and the second will not. The second thing is considered best practice because instanceof is not necessarily commutative (the value of a.equals(b) may not equal b.equals(a) ).
In particular, in this case, the ArrayList uses the AbstractList.equals() method, which simply checks that the other object is instanceof the List interface, so you're fine.
This is what you need to know.
What I would suggest is to do it a little differently:
List<String> list = new ArrayList<String>( Arrays.asList("hello", "goodbye") );
I am sure this is more verbose, but you are unlikely to get into trouble this way, since the resulting class is a "pure" ArrayList .
source share