Java 从队列转换为 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20708358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:44:11  来源:igfitidea点击:

Convert from Queue to ArrayList

javaarrayslistarraylistcasting

提问by user3120023

I want to change a queue containing numbers and operators into an ArrayList. I am coding in Java.

我想将包含数字和运算符的队列更改为 ArrayList。我正在用 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.

我希望这样做主要是为了我可以使用 RPN 来计算计算结果。

Is there a way to do this?

有没有办法做到这一点?

Thanks in advance for any help :)

在此先感谢您的帮助:)

回答by thatidiotguy

ArrayList list = new ArrayList(outputQueue);

回答by Prabhakaran Ramaswamy

Do like this

这样做

List list = new ArrayList(outputQueue);

回答by Brinnis

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.

而其他答案是创建ArrayList. 您可以简单地将其强制转换为List. 这将保留相同的底层数据结构 ( LinkedList),但您可以将其用作 List。

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 ArrayListis worth the the potential speed increase in accessing your data. Take a look at When to use LinkedList<> over ArrayList<>?.

天气与否这是做您需要的更好的方法取决于您如何使用列表。您必须决定创建新的成本ArrayList是否值得提高访问数据的潜在速度。看看什么时候在 ArrayList<> 上使用 LinkedList<>?.

回答by Chaitanya

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