ArrayList aList = new ArrayList();
List aList = new ArrayList();
What\'s the difference between these two and which is better to use and why?
I know of at least one case when declaring a variable with an interface does not work. When you want to use reflection.
I made a bug fix on some code where I declared a variable as Map
and assigned it an instance of HashMap
. This variable was used as a parameter in a method call that was accessed via reflection. The problem is that reflection tried to find a method with HashMap
signature and not the declared Map
signature. Since there was no method with a HashMap
as a parameter I was unable to find a method by reflection.
Map map = new HashMap();
public void test(Map m) {...};
Method m = this.getClass().getMethod("test", new Class>[]{map.getClass()});
Will not find the method that uses the interface. If you make another version of test that uses HashMap
instead then it will work - but now you are forced to declare your variable with a concrete class and not the more flexible interface...