I am new on Java and Android. I want to understand the following line:
List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
My doubt is: it is declared an object called listMap, which is of the type List of Map, right? But it is instantiated as an ArrayList. Sorry for the simple question, but Why is this possible?
ps1: I know List is an interface, so I can’t instantiate an object of an interface type.
ps2: I can declare listMap as being of the ArrayList type. What is the advantage of declare it as a List.
You are right,
Listis an Interface hence you will not be able to instantiate an Interface. You need to use some implementing class of the interface to instantiate.ArrayListis an implementation class of interfaceListand being used in the able statement.You can always, use
ArrayListin the left side as well i.e.Advantage of using Interface: If you want to use your variable object(listMap) across the classes then better to use the Interface as type, but if your variable object (lsitMap) locally within your program locally, then I don’t think there is any added advantage.
Now you will think about
Map, which is again an Interface. Please note that, you are not instantiating theMapobject through above statement. You are just mentioning that yourlistMaplist will contain the element ofMaptype.Again when you will try to instantiate elements to add in the
listMap, you will need an implementation class ofMapinterface e.gHashMapas below:Hope this makes things clear.