Home > Software engineering >  ArrayList vs LinkedList for bytes
ArrayList vs LinkedList for bytes

Time:11-11

I want to create a list of bytes. (In Java) The size is known. After every iteration, I'd like to remove the first element. And at any point in time, I will only be accessing the first element.

I thought about using a queue but that will not work in my use case as I need to keep the item in the list for multiple iterations.

What will be best suited keeping the performance in mind.

Array list of LinkedList? (Order is important) Since size is not changing, how about using array and accessing i-th element? Without removing the first everytime?

CodePudding user response:

For removal of first element an arrayList will be slower as it uses arrays to store data while a linkedList would be much faster O(1)

Refer blogs like; https://www.baeldung.com/java-remove-first-element-from-list#:~:text=ArrayList's remove() method,elements need to be shifted.

For removal of 1st element order does not matter anyway. So keeping performance in mind, LinkedList is the way to go for you.

For accessing a random i'th element however, an ArrayList is much faster O(1) than LinkedList O(n)

Refer the answer to question for more details to this or any further questions regarding LinkedList vs ArrayList: When to use LinkedList over ArrayList in Java?

CodePudding user response:

I am not sure if you want to implement this by yourself. If that's not the case, check Java Byte Class which is a byte primitive wrapper.

Regarding accessing the first element, there are multiples approaches, some of them are:

  1. Just simply iterating over the list with an index and then moving it to the last element and starting over again when the last element is reached.

  2. Poping the elements and adding them into another queue. When the last element is deleted you just simply change the queues and start over.

  • Related