队列是一种先进先出的一种数据结构。就像排队一样先到先买。从最后插入,从第一个拿出。这样就实现了一个简单队列
ArrayList 是基于我自己实现的动态数组的 有需求的朋友可以看看。https://blog.csdn.net/xulinglin520/article/details/81514153
/**
*
* @author XiaoTian
* @date 2018-08-09
* @param <E>
*/
public class Queue<E> {
ArrayList<E> arrayList;
/**
*
* @param capacity
*/
public Queue(int capacity){
arrayList = new ArrayList<>(capacity);
}
/**
* 无参构造器
*/
public Queue() {
arrayList = new ArrayList<>();
}
public int size() {
return arrayList.size();
}
/**
* 向队列末尾添加一个元素
* @param e
*/
public void push(E e) {
arrayList.add(e);
}
/**
* 取出队列第一个元素
*/
public void remove() {
arrayList.removeHead();
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty() {
return size() > 0;
}
/**
* 查看队列第一个元素
* @return
*/
public E getFront() {
return arrayList.get(0);
}
//打印(队列)
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < size(); i++) {
buffer.append(arrayList.get(i));
if(i < size()-1) {
buffer.append("->");
}
}
return "Stack [ arrayList = top | " +
buffer.toString()
+ " ] ";
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<>();
for (int i = 0; i < 10; i++) {
queue.push(i);
}
System.out.println(queue);
queue.remove();
System.out.println(queue);
queue.remove();
System.out.println(queue);
}
}
运行结果