数组模拟队列

来源:互联网 发布:什么叫数据标签 编辑:程序博客网 时间:2024/06/12 00:49
import java.lang.ref.SoftReference;/** * 使用数组模拟Java的队列 * 1.在队列尾添加元素void add(E e) * 2.删除队列头的元素E remove() * 3.访问队列头的元素E peek() * 4.获得队列大小int size() * 5.判断队列是否为空boolean isEmpty() * 6.清空队列void clear() * **/class QueueDemo<E>{private int LENGTH;private int SIZE;private int ADD;private int REMOVE;Object[] o;public QueueDemo(){this.SIZE=0;this.REMOVE=0;this.ADD=0;this.LENGTH=1;this.o=new Object[1];}public void add(E e){this.o[this.SIZE++]=e;this.ADD++;if(this.SIZE==this.LENGTH)this.copy();}public E remove(){if(this.ADD-this.REMOVE==0)throw new ArrayIndexOutOfBoundsException();E temp=(E)this.o[this.REMOVE++];this.o[this.REMOVE-1]=null;return temp;}public E peek(){if(this.ADD-this.REMOVE==0)throw new ArrayIndexOutOfBoundsException();return (E)this.o[this.SIZE-1];}public int size(){return this.ADD-this.REMOVE;}public boolean isEmpty(){if(this.ADD-this.REMOVE==0)return true;return false;}public void clear(){this.SIZE=0;this.REMOVE=0;this.ADD=0;this.LENGTH=1;this.o=new Object[1];}private void copy(){Object[] temp=new Object[this.LENGTH*2];this.LENGTH*=2;int count=0;SoftReference<Object[]> sr=new SoftReference<Object[]>(temp);for(int i=0;i<this.SIZE;i++)if(this.o[i]!=null)temp[count++]=this.o[i];this.o=temp;temp=null;this.SIZE=count;this.ADD=count;this.REMOVE=0;}public String toString(){if(this.ADD-this.REMOVE==0)return "[]";StringBuilder sb=new StringBuilder();SoftReference<StringBuilder> sr=new SoftReference<StringBuilder>(sb);sb.append("["); for(int i=this.REMOVE;i<this.SIZE-1;i++)sb.append(this.o[i]+","); sb.append(this.o[this.SIZE-1]+"]"); String str=sb.toString(); sb=null; return str;}}//测试用码public class QueueTest {public static void main(String[] args){QueueDemo<String> qd=new QueueDemo<String>();qd.add("aaaa");qd.add("llll");System.out.println(qd);System.out.println(qd.remove());System.out.println(qd);System.out.println(qd.remove());System.out.println(qd);System.out.println(qd.isEmpty());qd.add("pppp");qd.add("pppp");System.out.println(qd.size());System.out.println(qd.isEmpty());System.out.println(qd.peek());System.out.println(qd);}}

0 0
原创粉丝点击