数据结构之--通过数组实现队列
自己动手通过数组实现了个线程不安全的队列
代码如下:
import java.util.Iterator; public class ArrayQueue<T>{ private int CurrentSize; private int arrayLength; private static final int DEFAULT_SIZE = 2; private Object[] table; public ArrayQueue() { this(DEFAULT_SIZE); } public ArrayQueue(int size) { table = new Object[size]; arrayLength = size; CurrentSize = 0; } public void put(T t) { if (CurrentSize >= arrayLength) resize(2*arrayLength); table[CurrentSize++] = t; } private void resize(int s) { // TODO Auto-generated method stub assert s > arrayLength; Object[] newTable = new Object[s]; for(int i=0; i<arrayLength; i++) { newTable[i] = table[i]; } table = newTable; arrayLength = s; } public T get() { if (CurrentSize > 0) { Object o = table[0]; for(int i=0; i< CurrentSize; i++) { table[i] = table[i+1]; } table[CurrentSize--] = null; return (T)o; } return null; } public Iterator<T> iterator() { return new Itr(); } private class Itr implements Iterator<T> { private int itrIndex = 0; @Override public boolean hasNext() { // TODO Auto-generated method stub return itrIndex < CurrentSize; } @Override public T next() { // TODO Auto-generated method stub T t = (T)table[itrIndex++]; return t; } } }
测试代码:
import java.util.Iterator; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ArrayQueue<Integer> queue = new ArrayQueue(); queue.put(7); queue.put(1); queue.put(2); queue.put(3); queue.put(4); queue.put(5); queue.put(6); Iterator<Integer> itr = queue.iterator(); while(itr.hasNext()) System.out.println(itr.next()); queue.get(); Iterator<Integer> itrAfter = queue.iterator(); System.out.println("-------------"); while(itrAfter.hasNext()) System.out.println(itrAfter.next()); } }
后续加入线程安全考虑
posted on 2017-07-06 21:50 willowWind 阅读(169) 评论(0) 编辑 收藏 举报