ArrayList aList = new ArrayList();
List aList = new ArrayList();
What’s the difference between these two and which is better to use and why?
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.
List<T>is interface, whereArrayList<T>is class, and this class implementsList<T>interface.I would prefer 2nd form, which is more general, ie if you do not use methods specific to
ArrayList<T>you can declare its type as interfaceList<T>type. With 2nd form it will be easier to change implementation fromArrayList<T>to other class that implementsList<T>interface.EDIT:
As many of SO users commented both forms can be arguments to any method that accept
List<T>orArrrayList<T>. But when I declare method I would prefer interface:and use:
only when my method uses method specific to
ArrayList<T>, likeensureCapacity().Response with information that we should use typed
List<T>instead of justListis very good (of course if we do not use ancient Java).