Convert from Queue to ArrayList [duplicate]

2020-02-07 03:42发布

问题:

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 :)

回答1:

ArrayList list = new ArrayList(outputQueue);


回答2:

Do like this

List list = new ArrayList(outputQueue);


回答3:

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<>?.



回答4:

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);