自己实现的线性队列
程序员文章站
2022-07-14 14:04:41
...
package hjj.queue;
public class MyQueue<T> {
private int size;
private int capacity;
private Object[] queue;
public MyQueue() {
this(16);
}
public MyQueue(int capacity) {
if(capacity < 0) {
throw new RuntimeException("队列初始大小不能小于0");
}
this.capacity = capacity;
queue = new Object[capacity];
}
public void extendsCapacity() {
if(size == capacity) {
Object[] newQueue = new Object[capacity * 2 + 1];
for(int i=0; i<size; i++) {
newQueue[i] = queue[i];
}
capacity = capacity * 2 + 1;
queue = newQueue;
}
}
public boolean enQueue(T obj) {
extendsCapacity();
queue[size] = obj;
size++;
return true;
}
public T quitQueue() {
if(size == 0) {
return null;
}
T obj = (T)queue[0];
for(int i=0; i<size-1; i++) {
queue[i] = queue[i+1];
}
queue[size-1] = null;
size--;
return obj;
}
public int indexOf(T obj) {
for(int i=0; i<size; i++) {
if(queue[i].equals(obj)) {
return i;
}
}
return -1;
}
public T get(int index) {
if(index >= size) {
return null;
}
return (T)queue[index];
}
public int size() {
return size;
}
public int capacity() {
return capacity;
}
}
上一篇: kafka 获取metadata