Java 1.8使用数组实现循环队列
#代码知识 发布时间: 2026-01-12
本文实例为大家分享了Java 1.8使用数组实现循环队列的具体代码,供大家参考,具体内容如下

1、引入
使用数组实现循环队列,功能如下:
1)isFull():队列满?
2)isEmpty():队列空?
3)add():添加元素。
4)pop():移除元素。
5)display():展示队列。
6)getSize():获取当前队列元素个数。
2、代码
package DataStructure;
import java.util.Arrays;
/**
* @author: Inki
* @email: inki.yinji@qq.com
* @create: 2025 1022
* @last_modify: 2025 1023
*/
public class MyArrayQueue<AnyType> {
/**
* The default max size of my array queue.
*/
private final int DEFAULT_MAX_SIZE = 10;
/**
* The max size of my array queue.
*/
private int maxSize;
/**
* The front of my array queue.
*/
private int front;
/**
* The rear of my array queue.
*/
private int rear;
/**
* Using array to simulate queue.
*/
private AnyType[] arrQueue;
/**
* The first constructor.
*/
public MyArrayQueue() {
this(DEFAULT_MAX_SIZE);
}//Of the first constructor
/**
* The second constructor.
*/
public MyArrayQueue(int paraMaxSize) {
maxSize = paraMaxSize + 1;
arrQueue = (AnyType[]) new Object[maxSize];
front = 0;
rear = 0;
}//Of the second constructor
/**
* Queue is full?
* @return:
* True if full else false.
*/
public boolean isFull() {
return (rear + 1) % maxSize == front;
}//Of isFull
/**
* Queue is empty?
* @return:
* True if empty else false.
*/
public boolean isEmpty() {
return front == rear;
}//Of isEmpty
/**
* Add element.
* @param:
* paraVal:
* The given value.
*/
public void add(AnyType paraVal) {
if(isFull()) {
System.out.println("The queue is full.");
return;
}//Of if
arrQueue[rear] = paraVal;
rear = (rear + 1) % maxSize;
}//Of add
/**
* Pop element.
*/
public AnyType pop() {
if (isEmpty()) {
throw new RuntimeException("The queue is full.");
}//Of if
AnyType retVal = arrQueue[front];
front = (front + 1) % maxSize;
return retVal;
}//of pop
/**
* Display array queue.
*/
public void display() {
if (isEmpty()) {
System.out.println("The queue is empty.");
return;
}//Of if
System.out.print("The queue is: [");
int i = front;
while (i != (rear + maxSize- 1) % maxSize) {
System.out.printf("%s, ", arrQueue[i]);
i = (i + 1) % maxSize;
}//Of while
System.out.printf("%s]", arrQueue[rear - 1]);
}//Of display
/**
* Get current size of my array queue.
*/
public int getSize() {
return (rear - front + maxSize) % maxSize + 1;
}//Of getSize
/**
* The main
**/
public static void main(String[] args) {
MyArrayQueue <Integer> testArrayQueue = new MyArrayQueue<>(3);
testArrayQueue.add(1);
testArrayQueue.add(2);
testArrayQueue.add(4);
testArrayQueue.pop();
testArrayQueue.display();
}//Of main
}//Of MyArrayQueue
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
代码知识SEO上一篇 : 谈谈MySQL中的隐式转换
下一篇 : 记一次MySQL的优化案例
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!