So, this is an efficiency question.
I have two collections - an ArrayList and a Stack. I use the stack because I needed some simple pop/push functionality for this bit of code. The ArrayList is essentially the out variable as this is a small section of code in the function.
So, I the variables are defined as such, then code is run to add elements to the stack.
ArrayList<String> out = new ArrayList<String>();
/* other code.. */
Stack<String> lineStack = new Stack<String>();
/* code that adds stuff to the stack */
The question is, now that I have a fully populated stack, how do I place it in the out ArrayList in a reverse order then from the pop order.
My first thought up solution was
while(!lineStack.empty()) {
out.add(0, lineStack.pop());
}
...which works, but I worry about the efficiency of adding an element to the beginning of the ArrayList (which forces all existing elements to need to shift.. it's a linked list (I believe).. big deal.. but still a concern). Also, I am running this through a loop... perhaps unnecessarily.
So, my second solution that didn't involve looping (at least in my code, i'm sure the back end calls are doing it).
List l = lineStack.subList(0, lineStack.size());
out.addAll(l);
I know I don't need to allocate the list, but it'll keep for cleaner code. However, I am not sure if this will give me a particularly helpful performance gain.
So, my question is: Which of these will likely be most efficient for SMALL to MEDIUM size sets? If there is a more efficient solution, what would it be?