Usually declaration type is interface type and initialization part has implementation type. what is differnce between List<String> list = new ArrayList<String> and ArrayList<String> list = new ArrayList<String>? What is difference beside polymorphism?
-
2Hint: it took me less than 10 seconds to find this answer. Next time, please you try to do that prior research.GhostCat– GhostCat2016-12-23 09:32:54 +00:00Commented Dec 23, 2016 at 9:32
Add a comment
|
2 Answers
There are no important differences. But if you use something like this
void doSomething(List list)
{}
you can use any object which extends the List class, but if you use something like this void doSomething(ArrayList list) {} you can use only ArrayList object and its subclasses.
4 Comments
Roshan Bade
Thanks, is there any easyness in terms of code edit in future if i use Interface(eg: List<String> list = new ArrayList<String>();
Ihor Dobrovolskyi
Yes, abstraction is one of the OOP's principles!
Roshan Bade
can you give me an example? ;)
Ihor Dobrovolskyi
Now, your list may be object of the ArrayList class, but lately it may be object of the LinkedList class. Read about Polymorphism to understand it better.
List is an interface and ArrayList is its implimentation class. We can't create object of interface because they are abstract but we can create reference of interface which is nothing but List list . Using this reference we can invoke methods of ArrayList.
1 Comment
Tom
This doesn't answer the question. It doesn't answer the differences between using
List<..> or ArrayList<..> as variable type.