在网上阅读一位Android五年经验大神分享的面试经历,提到有个公司面试官问了用数组写队列的实现方式,随即自己构思了一下,简单的写了一下。还有疏漏,可以优化的还很多,主要就是个想法。
class ArrayQueue<T> {
private int SIZE = 10;
private Object[] arr = new Object[SIZE];
private int foot;
public ArrayQueue() {}
public boolean isEmpty() {
return foot == 0;
}
public void put(T t) {
arr[foot] = t;
if (foot++ >= arr.length) {
Object[] nArr = new Object[arr.length + SIZE];
for (int i = 0; i < arr.length; i++) {
if (null != arr[i]) {
nArr[i] = arr[i];
} else {
break;
}
}
arr = nArr;
}
}
public void remove() {
if (!isEmpty()) {
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
arr[i + 1] = null;
}
foot--;
} else {
throw new RuntimeException("队列为空");
}
}
public int size() {
return foot;
}
@SuppressWarnings("unchecked")
public T get(int i) {
if (i < foot && i >= 0) {
return (T) arr[i];
} else {
throw new RuntimeException("下标为负数或越栈");
}
}
}
文末贴上大神面试分享的链接:http://www.diycode.cc/topics/165