0

我已经编写了一个 ObjectQueue 类来处理对象,但我也希望能够处理 LinkedList 类型,这样我将拥有一个使用链表的对象队列。这甚至可能吗?

基本上我想要类似的东西

ArrayList<LinkedList <Job> > data

除了:ObjectQueue<LinkedList <Job> > data

我怎么能修改我的班级:

public class ObjectQueue {
      private Object[] item;
      private int front;
      private int rear;
      private int size;


    public ObjectQueue() {
        size = 100;
        item = new Object[size];
        front = size-1;
        rear  = size-1;
    }

    public ObjectQueue(int max) {
        size = max;
        item = new Object[size];
        front = size-1;
        rear  = size-1;
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public boolean isFull() {
       return rear == size-1 ? front == 0 : front == rear+1;
    }

    public void clear() {
        front = size-1;
        rear  = size-1;
    }


    public void insert(Object x) {
        if (isFull()) {
            System.out.println("Insert Runtime Error: Queue Overflow");
            System.exit(1);
        }
        if (rear == size-1)         // or rear = (rear+1) % size;
            rear = 0;
        else
            rear++;
        item[rear] = x;
    }

    public Object remove() {
        if (isEmpty()) {
            System.out.println("Remove Runtime Error: Queue Underflow");
            System.exit(1);
        }
        if (front == size-1)            // or front = (front+1) % size;
            front = 0;
        else
            front++;
        return item[front];
    }

    public Object query() {
        if (isEmpty()) {
            System.out.println("Query Runtime Error: Queue Underflow");
            System.exit(1);
        }
        if (front == size-1)
            return item[0];
        else
            return item[front+1];
    }
}
4

1 回答 1

0

您需要使您的类通用:

public class ObjectQueue<T> {
    ...
    public void insert(T x) {
        ...
    }
    public T remove() {
        ...
    }
    ...
}
于 2012-10-07T20:40:28.520 回答