Java创建栈时常用Deque而不是Stack

Stack类

  • public class stack<E> extends Vector<E>
  • Stack类继承Vector类,Vector类线程安全但性能差。
  • Vector扩容一倍空间,ArrayList扩容一半空间。
  • Vector分配内存需要连续的存储空间。

Deque接口

  • Deque是一个双端队列接口,继承Queue接口。
  • Deque实现类为LinkedList、ArrayDeque、LinkedBlockingDeque,其中LinkedList最常用。
  • LinkedList为链表结构,插入元素能为null,扩容方便。

常用方法

  • 入栈push()。等效于addFirst()
  • 出栈poll()/pop(),栈为空时poll返回null,pop抛出异常。等效于removeFirst()
  • 查看栈顶peek(),为空时返回null。等效于peekFirst()
  • 入队offer()
  • 出队poll(),为空时返回null
  • 查看队首peek(),为空时返回null
posted @ 2022-03-04 17:12  zjcfrancis  阅读(189)  评论(0编辑  收藏  举报