队列就是允许在末尾添加元素,在头删除元素的一种数据结构
package com.sky.queue;
import java.util.Arrays;
/**
* 用数组来实现队列 实现队列的增加、移除、判断是否为空、清除队列操作
*
*/
public class SquenceQueue<T> {
private int SIZE = 10;
private int capacity;
private int front = 0;
private int rear = 0;
private Object[] objects;
/**
* 默认无元素的队列
*/
public SquenceQueue() {
capacity = SIZE;
objects = new Object[capacity];
}
/**
* 初始化一个长度
* @param initSize
*/
public SquenceQueue(int initSize) {
capacity = initSize;
objects = new Object[capacity];
}
/**
* 初始化时赋予队列一个元素
* @param object
*/
public SquenceQueue(T object) {
capacity = SIZE;
objects = new Object[capacity];
objects[rear] = object;
rear++;
}
/**
* 初始化时给队列一个初始长度
* @param object
* @param initSize
*/
public SquenceQueue(T object,int initSize) {
this.capacity = initSize;
objects = new Object[capacity];
objects[rear] = object;
rear++;
}
/**
* 返回队列长度
* @return
*/
public int length() {
return rear - front;
}
/**
* 判断数组是否为空
* @return
*/
public boolean empty() {
return length() == 0;
}
/**
* 移除队列前元素
* @return
*/
@SuppressWarnings("unchecked")
public T remove() {
if (empty()) {
throw new IndexOutOfBoundsException("数组越界");
}
T oldValue = (T)objects[front];
objects[front] = null;
front++;
return oldValue;
}
/**
* 返回队列第一个元素,但不删除
* @return
*/
@SuppressWarnings("unchecked")
public T element() {
if (empty()) {
return null;
}
return (T)objects[front];
}
/**
* 添加元素
* @param element
*/
public void add(T element) {
if (rear > capacity - 1) {
throw new IndexOutOfBoundsException();
}
objects[rear++] = element;
}
/**
* 将队列全部清除
*/
public void clear() {
Arrays.fill(objects, null);
front = 0;
rear = 0;
}
@Override
public String toString() {
return "SquenceQueue [objects=" + Arrays.toString(objects) + "]";
}
}