Why we use,
Map abc = new HashMap(20);
instead of
HashMap abc = new HashMap(20);
please help me to find out the differnce between these two.
would be grateful for help.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the first case, the
abcvariable is of typeHashMap, which is an implementation of theMapinterface. If you change your mind later and want to use aTreeMapfor instance, you will have to change many references toHashMapin your code, and is is possible you used peculiarities ofHashMapwhere the genericMapoperations are enough.If you use the
Mapinterface as type for you variable, you can change the implementation easily.It is important when you design classes for reuse. If you have a method that takes a
Mapas argument, anyMapimplementation will be usable to call your method. Thus, the caller will be free to use the most suitable implementation.