This question already has answers here:
Closed 6 years ago.
I want to change a queue containing numbers and operators into an ArrayList.
I am coding in Java.
Currently my Queue is defined as follows:
Queue outputQueue = new LinkedList();
The queue currently contains the following data:
[1, 9, 3, /, 4, 3, -, 2, /, *, +]
I wish to do this mainly so i can use RPN to calculate the result of the calculation.
Is there a way to do this?
Thanks in advance for any help :)
ArrayList list = new ArrayList(outputQueue);
Do like this
List list = new ArrayList(outputQueue);
While the other answers are the correct way to create an ArrayList
. You could simply cast it to a List
. This would leave the same underlying data structure (LinkedList
) but you can use it as a List then.
Queue outputQueue = new LinkedList();
List list = (List)outputQueue;
Weather or not this is a better way to do what you need depends on how you are using the List. You have to decide if the cost of create a new ArrayList
is worth the the potential speed increase in accessing your data. Take a look at When to use LinkedList<> over ArrayList<>?.
Code like this
Queue outputQueue = new LinkedList();
outputQueue.add("1");
outputQueue.add("9");
outputQueue.add("3");
outputQueue.add("/");
outputQueue.add("4");
outputQueue.add("3");
outputQueue.add("-");
outputQueue.add("2");
outputQueue.add("*");
outputQueue.add("+");
ArrayList arraylist = new ArrayList(outputQueue);