Reputation: 2833
I'm making a top-bottom queue. Do I use array or arraylist?
Upvotes: 1
Views: 1373
Reputation: 310957
I wouldn't use either an array or an ArrayList
. I would use a LinkedList
. You need to insert at the back and remove from the front, and these operations are O(n) on arrays, and O(1) on linked lists.
Upvotes: 0
Reputation: 328659
You could use a LinkedBlockingQueue or an ArrayBlockingQueue which can be bounded (fixed size). An array could be a solution but you would need to reimplement the queue logic. Lists are not bounded so nothing prevents you from making them bigger than expected, unless you add some code. The queues do all that for you.
Upvotes: 0
Reputation: 5173
I'm not sure what you mean by "top-bottom" queue, and neither does google, but in general an array is not a good choice for a queue. In queues, you insert at the front and remove from the back (FIFO). In an array, insertion to the front of the array requires copying all of the elements in the existing array over to the right one, requiring O(n) time. If you only have a few items in the queue, that's not much of an issue, but if you have a lot of items, it's obviously very wasteful.
A doubly linked list with head and tail pointers would be better, but you should just use a Queue instead.
Upvotes: 1
Reputation: 34563
I'd use ArrayList
, since it's effectively an array with a nicer API. Use the constructor that takes an initialCapacity
argument to make it allocate the right amount of memory up-front, and don't call any methods that would cause it to resize itself.
Upvotes: 1
Reputation: 805
If it is fixed as you said above, i.e. it always will have up to 10 things, I'd use a array because arrays are fixed and they are more maneuverable. The arraylist can grow, but the API for it is a lot smaller than the array.
Upvotes: 1
Reputation: 21034
Depends on how you are going to fill it:
If you are going to fill it in random order, you may be better with an array, otherwise I'd go with ArrayList or List to avoid all the "Redim"s.
Upvotes: 0