在java中使用Array实现队列

队列是一种特殊类型的集合,旨在在处理之前保存元素,并以FIFO(先进先出)方式对元素进行排序。 它是java集合框架的一部分。

在这里,尝试使用数组实现Queue,并提供基本功能,如:enqueue(obj)dequeue()isEmpty()


package com.jb51.cc.util;

//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 class MyQueue {

    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);
        //queue.enqueue(7);
        //queue.enqueue(8);
    }

}

上面的类是一个简单队列,它的大小是固定的,它会在满时抛出异常。

可以像使用ArrayList实现使大小动态化。ArrayList实现并尝试在运行时实现队列大小的增加

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...