用数组实现了一个环形队列,怎么优化下?

miracleliu 2013-12-26 04:59:07

用数组实现了一个环形队列,怎么优化下?

初步想法,1、用泛型,2、改成接口(以便用链表等其他的方式来实现)

还有其他的可以改善的地方吗?

package excise;

public class QueueTest {
public static void main(String[] args) {

QueueTest qt = new QueueTest();
try {
qt.add(9);
qt.add(10);
qt.add(8);
qt.add(1);
System.out.println(qt.poll());
qt.add(10249);
qt.add(40);
System.out.println(qt.poll());
System.out.println(qt.poll());
qt.add(66);
System.out.println(qt.poll());
} catch (Exception e) {
e.printStackTrace();
}

}

int head = 0;
int end = head;
int len = 5;
int cur = 0;
int[] arr = new int[len];

public void print() {
for (int i = 0; i < len; i++) {
System.out.print(arr[i] + ",");
}
System.out.println();
}

public void add(int ele) throws Exception {

if (cur >= 5) {
throw new Exception("full");
}
else {
arr[end] = ele;
cur++;
end++;
if (end >= len) {
end = 0;
}
}

print();
}

public int poll() throws Exception {

if (cur == 0) {
throw new Exception("empty");
}

int ret = arr[head];
head++;
if (head >= len) {
head = 0;
}
cur--;
print();

return ret;
}
}
...全文
624 4 打赏 收藏 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
miracleliu 2014-01-02
  • 打赏
  • 举报
回复
引用 3 楼 Inhibitory 的回复:
这个是我写的,可以参考一下
package com.tur.iterator;

import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 循环队列。
 * 在有的场景下非常有用,不停的接首传感器传来的数据,显示到界面上。
 * 开辟一个容量为200的循环队列,用于保存新收到的200个传感器数据,
 * 新接收到的数据覆盖前面的数据,需要显示的是最近新收到的数据,
 * 比这200个还早的数据没有必要继续保存。
 * 显示的GUI类遍历队列的数据绘制到界面上。
 *
 * ArrayBlockingQueue: 用循环数组实现的Queue
 *
 * for each 循环可以和任何实现了Iterable<E>接口的对象一起工作。
 */
public class CircularQueue<T> implements Iterable<T> {
    private int head = 0;
    private int size = 0;
    private int capacity = 0;
    private int modifiedCount = 0;
    private T[] data = null;

    /**
     * 创建能够容纳16个元素的循环队列。
     */
    public CircularQueue() {
        this(16);
    }

    /**
     * 创建能够容纳capacity个元素的循环队列。
     * 如果capacity小于等于0,则capacity取1。
     * @param capacity 队列的容量。
     */
    public CircularQueue(int capacity) {
        capacity = capacity > 0 ? capacity : 1;
        this.capacity = capacity;
        data = (T[]) new Object[capacity];
    }

    /**
     * 在队尾加入一个元素。
     * 如果当前队列的元素个数为其capacity,则新加入的元素放在原来的队首,队列的head后移动一个位置。
     * @param element 要加入对尾的元素。
     */
    public void enqueue(T element) {
        int index = calculateIndex(size);
        data[index] = element;
        size++;
        modifiedCount++;

        if (size > capacity) {
            size = capacity;
            head = calculateIndex(1);
        }
    }

    /**
     * 删除队首元素。
     * 但没有元素可删除时抛出一个运行时异常。
     * @return 队首的元素。
     */
    public T dequeue() {
        if (size == 0) {
            throw new NoSuchElementException("There is no element");
        }

        T r = data[head];
        head = calculateIndex(1);
        size--;
        modifiedCount++;

        return r;
    }

    /**
     * 取得队首元素。
     * 如果队列是空的抛出一个运行时异常。
     * @return 队首元素。
     */
    public T peek() {
        if (size == 0) {
            throw new NoSuchElementException("There is no element");
        }

        return data[head];
    }

    /**
     * 取得队列中元素的个数。
     * @return 队列中元素的个数。
     */
    public int size() {
        return size;
    }

    /**
     * 返回一个Iterator用来顺序遍历队列。
     * @return iterator.
     */
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int offset = 0;
            private int modCount = modifiedCount;

            @Override
            public boolean hasNext() {
                return offset < size;
            }

            @Override
            public T next() {
                // 在遍历队列的时候如果队列被修改了则抛出异常。
                if (modCount != modifiedCount) {
                    throw new ConcurrentModificationException("The queue is modified when iteration.");
                }

                return data[calculateIndex(offset++)];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove() is unsupported.");
            }
        };
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append("[");

//        Iterator<T> iter = iterator();
//        while (iter.hasNext()) {
//            sb.append(iter.next() + ", ");
//        }

        for (T elem : this) {
            sb.append(elem + ", ");
        }

        sb.append("]");

        return String.format("Logical: %s <-----> Physical: %s", sb.toString().replaceAll(", ]$", "]"), Arrays.toString(data));
    }

    /**
     * 取得index在队列里真实的下标。
     * @param offset
     * @return 传入的index在队列里对应的下标。
     */
    private int calculateIndex(int offset) {
        return (head + offset) % capacity;
    }
}
赞!学到了Iterator。
Inhibitory 2014-01-02
  • 打赏
  • 举报
回复
这个是我写的,可以参考一下
package com.tur.iterator;

import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 循环队列。
 * 在有的场景下非常有用,不停的接首传感器传来的数据,显示到界面上。
 * 开辟一个容量为200的循环队列,用于保存新收到的200个传感器数据,
 * 新接收到的数据覆盖前面的数据,需要显示的是最近新收到的数据,
 * 比这200个还早的数据没有必要继续保存。
 * 显示的GUI类遍历队列的数据绘制到界面上。
 *
 * ArrayBlockingQueue: 用循环数组实现的Queue
 *
 * for each 循环可以和任何实现了Iterable<E>接口的对象一起工作。
 */
public class CircularQueue<T> implements Iterable<T> {
    private int head = 0;
    private int size = 0;
    private int capacity = 0;
    private int modifiedCount = 0;
    private T[] data = null;

    /**
     * 创建能够容纳16个元素的循环队列。
     */
    public CircularQueue() {
        this(16);
    }

    /**
     * 创建能够容纳capacity个元素的循环队列。
     * 如果capacity小于等于0,则capacity取1。
     * @param capacity 队列的容量。
     */
    public CircularQueue(int capacity) {
        capacity = capacity > 0 ? capacity : 1;
        this.capacity = capacity;
        data = (T[]) new Object[capacity];
    }

    /**
     * 在队尾加入一个元素。
     * 如果当前队列的元素个数为其capacity,则新加入的元素放在原来的队首,队列的head后移动一个位置。
     * @param element 要加入对尾的元素。
     */
    public void enqueue(T element) {
        int index = calculateIndex(size);
        data[index] = element;
        size++;
        modifiedCount++;

        if (size > capacity) {
            size = capacity;
            head = calculateIndex(1);
        }
    }

    /**
     * 删除队首元素。
     * 但没有元素可删除时抛出一个运行时异常。
     * @return 队首的元素。
     */
    public T dequeue() {
        if (size == 0) {
            throw new NoSuchElementException("There is no element");
        }

        T r = data[head];
        head = calculateIndex(1);
        size--;
        modifiedCount++;

        return r;
    }

    /**
     * 取得队首元素。
     * 如果队列是空的抛出一个运行时异常。
     * @return 队首元素。
     */
    public T peek() {
        if (size == 0) {
            throw new NoSuchElementException("There is no element");
        }

        return data[head];
    }

    /**
     * 取得队列中元素的个数。
     * @return 队列中元素的个数。
     */
    public int size() {
        return size;
    }

    /**
     * 返回一个Iterator用来顺序遍历队列。
     * @return iterator.
     */
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int offset = 0;
            private int modCount = modifiedCount;

            @Override
            public boolean hasNext() {
                return offset < size;
            }

            @Override
            public T next() {
                // 在遍历队列的时候如果队列被修改了则抛出异常。
                if (modCount != modifiedCount) {
                    throw new ConcurrentModificationException("The queue is modified when iteration.");
                }

                return data[calculateIndex(offset++)];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove() is unsupported.");
            }
        };
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append("[");

//        Iterator<T> iter = iterator();
//        while (iter.hasNext()) {
//            sb.append(iter.next() + ", ");
//        }

        for (T elem : this) {
            sb.append(elem + ", ");
        }

        sb.append("]");

        return String.format("Logical: %s <-----> Physical: %s", sb.toString().replaceAll(", ]$", "]"), Arrays.toString(data));
    }

    /**
     * 取得index在队列里真实的下标。
     * @param offset
     * @return 传入的index在队列里对应的下标。
     */
    private int calculateIndex(int offset) {
        return (head + offset) % capacity;
    }
}
miracleliu 2014-01-02
  • 打赏
  • 举报
回复
改成了泛型的
public class CircleQueue<E> {

	private int head = 0;
	private int end = 0;
	private int lenth = 5;
	private int cur = 0;
	private E[] arr;
	
	public CircleQueue() {
		arr = (E[]) new Object[10];
	}

	public CircleQueue(int size) {
		arr = (E[]) new Object[size];
	}
	
	public void print() {
		for (int i = 0; i < lenth; i++) {
			System.out.print(arr[i] + ",");
		}
		System.out.println();
	}

	public void add(E ele) throws Exception {

		if (cur >= 5) {
			throw new Exception("full");
		}
		else {
			arr[end] = ele;
			cur++;
			end++;
			if (end >= lenth) {
				end = 0;
			}
		}
		print();
	}

	public E poll() throws Exception {

		if (cur == 0) {
			throw new Exception("empty");
		}

		E ret = arr[head];
		head++;
		if (head >= lenth) {
			head = 0;
		}
		cur--;
		print();

		return ret;
	}

	public E peek() {
		E ret = arr[head];
		return ret;
	}

}
 
teemai 2013-12-26
  • 打赏
  • 举报
回复
应该支持存入对象吧

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧