自定义Queue

Queue(队列)是一种特殊类型的集合,旨在使用先进先出方式处理和排序之前保存元素。

下面使用 Array 实现 Queue,并提供诸如enqueue(obj),dequeue()和isEmpty()等基本功能。

/**
 * 

* * @author 三产 * @version 1.0 * @date 2017-03-24 * @QQGroup 213732117 * @website http://www.coderknock.com * @copyright Copyright 2017 拿客 coderknock.com All rights reserved. * @since JDK 1.8 */
public class MyQueue { //CONSTRUCTION: with no initializer // // ******************PUBLIC OPERATIONS********************* // void enqueue( obj ) --> Insert obj // Object dequeue( ) --> Return and remove least recent item // boolean isEmpty( ) --> Return true if empty; else false public static final int DEFAULT_SIZE=5; private Object data[]; private int index; public MyQueue(){ data=new Object[DEFAULT_SIZE]; } public boolean isEmpty(){ return index==0; } public void enqueue(Object obj) throws Exception{ if(index==DEFAULT_SIZE-1){ throw new Exception("Queue is full. Dequeue some objects"); } this.data[index]=obj; this.index++; } public Object dequeue() throws Exception{ if(isEmpty())throw new Exception("Queue is empty"); Object obj=this.data[0]; for(int i =0; i<this.index-1; i++){ data[i]=data[i+1]; } this.index--; return obj; } public static void main(String[] args) throws Exception { MyQueue queue = new MyQueue(); queue.enqueue("1"); System.out.println(queue.dequeue()); queue.enqueue("2"); queue.enqueue("3"); queue.enqueue("4"); System.out.println(queue.dequeue()); queue.enqueue("5"); queue.enqueue("6"); System.out.println(queue.dequeue()); queue.enqueue("7"); /** * 这里是队列超出默认大小的时候会抛出的异常 * Exception in thread "main" java.lang.Exception: Queue is full. Dequeue some objects * at MyQueue.enqueue(MyQueue.java:37) * at MyQueue.main(MyQueue.java:69) */ queue.enqueue("8"); System.out.println(queue.dequeue()); } }

你可能感兴趣的:(自定义JDK中数结构)