Talking about computer science we have some good questions and different approaches to choose the first one that appears when we are studying computer science is when use Array and when use Linked Lists, and today I'll answer this question, or at least try to answer for you.
Differences
First, let's talk about the differences between these two types of variables. The most important difference between arrays and linked lists are, arrays are storage in sequential slots in memory, for example if I have an array with 10 items, and I need to store this array I need to find a space in memory with 10 slots one next to each other something like this:
As You see we need at least 10 slots one next to each other to store an array in a memory, so if we only have 9 we cannot store this array. But this way of work can help us with some problems, like:
- If You want to know the value of a random item of the array you can find it just accessing the position in the slots that you want, that is such more difficult when we are working with linked lists, you will see in a little.
With Linked Lists we have a different approach to store data, Linked Lists store the memory address of the next position inside the actual position, and because this we can store a Linked List with 10 items without have a 10 slots close to themselves inside the memory something like this:
Again in Linked Lists we don't need to put the items close to themselves, we just put in an empty slot of the memory and after link to the last item of the list, this functionality can help us with this case:
- If I want to add a new data inside the list, I can just put the data inside any empty slot on memory and link it to the last position of the list, easy.
- If I want to delete an item of the list, I can just change the memory address of the position that I want to the position of the value to replace, and then delete the value of I want, easy too.
In a first time you can think that lists are better than arrays, but it's not true, we can use both in different circumstances like I said in this post, Arrays are better to search things inside them, but they are not when we want to add or delete items from them, but Linked Lists are better to add and remove items, but no to search inside them, because you always need to pass by any position to find the next one.
So, they have differences, and it's our job to find the best to solve our problem, when we need to save a data, and we don't need to search a random item inside them let's use a Linked List, but we need to search something randomly inside, let's use an Array and be happy =].
Top comments (0)