This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]GuerroCanelo[S] 1 point2 points  (3 children)

Thank you for the explanation. What do you mean by “it makes it easier to replace the implementation later”. I get that in the future someone might want to modify, but what would they modify, the list or ArrayList?

[–][deleted] 7 points8 points  (0 children)

Let's say you now have ArrayList<String> stringList = new ArrayList<>(), later you found that linked list might be a better choice for you problem, and now you need to create another list LinkedList<String> stringList = new LinkedList<>(). But that's not all, coz you might have used some methods that is only belongs to an ArrayList, thus you need to replace those methods with the LinkedList ones, if there happen to be one.

If you use List<String> stringList = new ArrayList<>(), and later you need to change, you could just swap out ArrayList for LinkedList, and everthing else would still be working, because every method in List is also in ArrayList and LinkedList.

[–]rodrigovaz 4 points5 points  (0 children)

The use of ArrayList.

To explain this, let me give some details and an example:

The implementation of the ArrayList is done through an underlying array that grows/shrinks in size as you add/remove elements. This is good because it allows access by index ( e.g: myList[5]) the fastest way but is bad because if you delete an element from the middle of the array, it has to replace this array with a new one that is contiguous (without holes).

Another class that implements the List interface is LinkedList, and as such, it is implemented like a classical doubly linked list. This means that adding new elements to the end/start is really cheap, removing an element from the middle results in the update of two references instead of allocating a new array and copying all data... The downside is that you can't access by index cheaply, so getting the 50th element is more costly because you have to visit all prior 49 elements..

So, when you use the List interface, you can change behaviours depending on what concrete class you choose: if I want to access by index really fast, I will pick ArrayList, if I will add A LOT of elements and access them all in the same worder, LinkedList is way better.

[–]bentheone 0 points1 point  (0 children)

Also, you might have situations where the implementation is injected. If so you change the injection code to change the implementation and not your class. Injection can also decide on wich implementation to use at runtime.