在我的应用程序中,我有一个由 4 个元素组成的队列,每个元素都是一个 HashMap
BlockingQueue<HashMap<Integer, double[]>> myInput;
我现在能够提取所有 4 个组件,执行以下操作:
try {
firstElement = myInput.take();
} catch (InterruptedException ex) {
Logger.getLogger(DirectionOfArrival.class.getName()).log(Level.SEVERE, null, ex);
}
try {
secondElement = myInput.take();
} catch (InterruptedException ex) {
Logger.getLogger(DirectionOfArrival.class.getName()).log(Level.SEVERE, null, ex);
}
try {
thirdElement = myInput.take();
} catch (InterruptedException ex) {
Logger.getLogger(DirectionOfArrival.class.getName()).log(Level.SEVERE, null, ex);
}
try {
fourthElement = myInput.take();
} catch (InterruptedException ex) {
Logger.getLogger(DirectionOfArrival.class.getName()).log(Level.SEVERE, null, ex);
}
最终得到:
firstElement
secondElement
thirdElement
fourthElement
我想问一下,当使用不止4个元素组成的队列时,如何执行上述操作(其中很容易获得firstElement、secondElement、thirdElement、fourthElement) ,但是例如一个由 400 个元素组成的队列(重要的是要指出,即使在这种情况下我也想获得像firstElement,secondElement,..., 第 400 个元素)。
有没有一种快速而优雅的方法来做到这一点?
任何帮助将不胜感激
提前非常感谢
最佳答案
Is there a fast and elegant way to do it?
使用循环。
将提取的元素存储在
List
或数组中。或者在提取它们时对其进行处理。不要使用诸如
firstElement
、secondElement
等命名变量。它与优雅相反。如果您需要命名 400 个左右的元素(使用有意义的名称!),请考虑使用HashMap
。
关于JAVA - 提取并存储所有队列元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51155439/