Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help choosing the right data structure

I need a data structure with the following requirements:

  1. Needs to be able to get elements by index (like a List).
  2. I will always just add / remove elements from the end of the structure.

I am inclined to use an ArrayList. In this situation, it seems to be O(1) both to read elements (they always are?), remove elements (I only need to remove them at the end of the list) and to add(I only add to the end of the list).

There is only the problem that time to time the ArrayList will have a performance penalty when it's completly full and I need to add more elements to it.

Is there any other better idea? I don't think of a data structure that'd beat the ArrayList here.

Thanks

like image 642
devoured elysium Avatar asked Dec 28 '22 15:12

devoured elysium


1 Answers

Sounds good, though in C# you should use a List<T>. It's the Java equivalent of ArrayList<E>. The ArrayList class in C# is not generic and is basically made obsolete by the new List<T> class.

There is only the problem that time to time the ArrayList will have a performance penalty when it's completely full and I need to add more elements to it.

This probably won't be a problem and you probably shouldn't worry about it unless you've performance profiled. However if you know (or can guess) in advance the number of elements that your list will contain you can set its Capacity to that value (ensureCapacity in Java). This will cause the list to reserve the required memory in advance. You can also give the capacity to the list constructor in both languages.

like image 52
Mark Byers Avatar answered Jan 01 '23 16:01

Mark Byers