我是 Java 新手,正在学习集合主题。谁能告诉我为什么在 ArrayDeque 和 Stack 中使用 push 方法时输出会有所不同?
ArrayDeque示例程序:
public class Simple4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayDeque q = new ArrayDeque();
q.push("e");
q.push("f");
System.out.println(q);
}
}
输出: [f, e]
堆栈示例程序:
public class Simple5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack s = new Stack();
s.push("apple");
s.push("banana");
System.out.println(s);
}
}
输出: [苹果,香蕉]
最佳答案
您的示例都是原始类型。不要使用原始类型。此外,您的 Stack 正在使用 Collection 的默认输出格式 - 请注意,元素按 FIFO 顺序(而不是 LIFO)排列。要正确使用Stack
,请使用pop()
。就像,
Stack<String> s = new Stack<>();
s.push("apple");
s.push("banana");
while (!s.isEmpty()) {
System.out.println(s.pop());
}
哪个输出(后进先出)类似于
banana
apple
关于java - 为什么在ArrayDeque和Stack中使用push()方法时输出不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554429/