Java Collection Framework

José Carreño
3 min readApr 22, 2021

When people is learning to write code in Java (whichever version what you want), is common to learn how you can group objects in a list which that you can iterate. Most of the time, we use an ArrayList for it and maybe it going to works, but is not the only one tool, also there are many options that we can use and maybe get more performance for our applications.

Java Collection Framework provide us a set of tools and we just need to choose the best option for solve our problem, even, ArrayList is one of them.

LinkedList

LinkedList is a collection which can contain many objects of the same type, is too similar to an ArrayList and has the same methods. The reason of that is LinkedList and ArrayList both are implementations of List interface. The difference between them, is the ArrayList has a simple array inside it, so when an element is added, this element is added to the array, if the array length is not enough for the elements quantity, the array is replaced for another one. In a LinkedList, every element that is added, is an object which can be placed in different memory positions. The LinkedList has a link to the first element, this element has a link to the next element in the collection. Elements in the middle of the collection, have a link to the previous element and another link to the next element and so on. The advantage in a LinkedList over an ArrayList, is when we need to read, modify, add or delete elements inside of it cause has more performance. The drawback is you can’t access to a random element in the collection, in that case we need use an ArrayList. Let’s see an example:

In the picture above, we can see some things that we can’t do with an ArrayList, like Add an element at the beginning of the collection and add an element in the middle of the collection.

Stack

Stack is another type of collection. It follow the last-in-first-out principle. Stack extends the Vector class and maybe is the easiest type of collection to understand how it works. The last element added to the collection is going to be the first element in get out. Let’s see a simple example:

In the picture above, the output it will be 3 cause was the last element added to the collection. If we try to execute pop method again, the removed element it will be the number 2.

ArrayDeque

When we need to work with first-in-first-out principle, We should use ArrayDeque. With this ypeof collection, we can add elements at the top of it and at the end.

--

--

José Carreño
0 Followers

I’m a software developer, with passion for technologies and research for build innovative solutions.