I am learning Collections in CoreJava book and I found this code:
List<String> a = new LinkedList<String>();
Now I wonder why this code isn’t like this:
LinkedList<String> a = new LinkedList<String>();
Why we declare a as List?
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.
The code:
is better than:
This is because if you declared
listasListand you found that the performance of the program is not good, you could change the code to:and see if the program runs faster. The beauty of this is that you can make that change without having to change the rest of the code.
As a conclusion, if possible, declare a reference as an interface (
Listis an interface):and you can easily switch the implementation (
class ArrayListandclass LinkedListare implementations of the interfaceList):or