队列java实现之线性存储源码
class Queue<T>{
private int size = 0;
private int length;
private final int default_length = 20;
private Object[] o;
public Queue(){
length = default_length;
o = new Object[length];
}
public Queue(T data,int init_length){
length = init_length;
o = new Object[length];
o[size] = data;
size++;
}
public int getSize(){
return size;
}
//进队列
public void add(T data){
if(size+1>length){
length *=2;
Object[] temp = new Object[length];
int i=0;
while(i<size){
temp[i] = o[i];
o[i--]=null;
}
o = temp;
}
o[size++] = data;
}
//出队列
public T remove(){
if(isEmpty()){
throw new NullPointerException("空队列");
}
@SuppressWarnings("unchecked")
T oldvalue = (T) o[0];
int i = 0;
while(i<size-1){
o[i] = o[i+1];
i++;
}
o[i] = null;
size--;
return oldvalue;
}
public void clear(){
while(size-->0){
o[size] = null;
}
}
public boolean isEmpty(){
if(size>0){
return false;
}else
return true;
}
@Override
public String toString() {
if(size == 0){
return "[]";
}else{
StringBuffer sb = new StringBuffer("[");
int i=0;
while(i<size){
sb.append(o[i++]+",");
}
return sb.delete(sb.length()-1, sb.length()).toString()+"]";
}
}
}