數組實現隊列

來源:互聯網
上載者:User
import java.util.Arrays;/** * 用數組實現隊列 */@SuppressWarnings("unchecked")public class Queue<T> {private int DEFAULT_SIZE = 10;private int capacity;private Object[] elementData;private int front = 0;private int rear = 0;public Queue(){capacity = DEFAULT_SIZE;elementData = new Object[capacity];}public Queue(T element){this();elementData[0] = element;rear++;}public Queue(T element , int initSize){this.capacity = initSize;elementData = new Object[capacity];elementData[0] = element;rear++;}public int size(){return rear - front;}public void add(T element){if (rear > capacity - 1){throw new IndexOutOfBoundsException("the queue is full!");}elementData[rear++] = element;}    public T remove(){if (empty()){throw new IndexOutOfBoundsException("queue is empty");}T oldValue = (T)elementData[front];elementData[front++] = null; return oldValue;}    public T element() {          if (empty()){              throw new IndexOutOfBoundsException("queue is empty");          }          return (T)elementData[front];      }  public boolean empty(){return rear == front;}public void clear(){Arrays.fill(elementData , null);front = 0;rear = 0;}public String toString(){if (empty()){return "[]";}else{StringBuilder sb = new StringBuilder("[");for (int i = front  ; i < rear ; i++ ){sb.append(elementData[i].toString() + ", ");}int len = sb.length();return sb.delete(len - 2 , len).append("]").toString();}}public static void main(String[] args){Queue<String> queue = new Queue<String>("ABs", 20);queue.add("DEF");queue.add("egg");//System.out.println(queue.empty());//System.out.println(queue.size());System.out.println(queue.element());//queue.clear();//System.out.println(queue.empty());//System.out.println(queue.size());}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.