請問關於ArrayList的問題

Implement a priority queue capable of holding objects of an arbitrary type, T,by defining a PriorityQueue class that implements the queue with an ArrayList. A priority queue is a type of list where every item added to the queue also has an associated priority. Define priority in your application so that those items with the largest numerical value have the highest priority. Your class should support the following methods:

1.Add(item, priority)---Adds a new item to the queue with the associated priority.

2.Remove()---Returns the item with the highest priority and removes it from the queue.If the user attempts to remove from an empty queue return null.

For example, if q is a priority queue defined to take strings:

a.add("X", 10);

a.add("Y", 1);

a.add("Z", 3);

System.out.println(q.remove());//Returns X

System.out.println(q.remove());//Returns Y

System.out.println(q.remove());//Returns Z

Test your queue on data with priorities in various orders. You can implement the priority queue by performing a linear search through the ArrayList.

拜託會的大大幫幫忙喔!!

感激不盡阿=ˇ=

Update:

有好多錯誤喔!!是yahoo字的問題嗎??

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    import java.util.ArrayList;

    public class PriorityQueue {

    //用來儲存OBJECT的ARRAY LIST

    private ArrayList objectList;

    //用來儲存PRIORITY的ARRAY LIST

    private ArrayList priorityList;

    //建構子

    public PriorityQueue() {

    objectList = new ArrayList();

    priorityList = new ArrayList();

    }

    //把OBJECT加入PRIORITY LIST

    public void add(int priority, Object object) {

    objectList.add(object);

    priorityList.add(new Integer(priority));

    }

    //從PRIORITY LIST中取的高PRIORITY的OBJECT

    public Object remove() {

    Object returnObject = null;

    Object [] priorityArray = priorityList.toArray();

    int outCounter = 0;

    int temp = ((Integer)priorityArray[0]).intValue();

    //找出最高PRIORITY的位置

    for (int i = 0; i < priorityArray.length; i++) {

    if (temp ((Integer)priorityArray[i]).intValue()) {

    temp = ((Integer)priorityArray[i]).intValue();

    outCounter = i;

    }

    }

    //移除PRIORITY

    priorityList.remove(outCounter);

    //取得並移除高PRIORITY的OBJECT

    returnObject = objectList.remove(outCounter);

    return returnObject;

    }

    //取得PRIORITY QUEUE裡是否還有OBJECT

    public boolean hasNext() {

    if (objectList.size() > 0) {

    return true;

    }

    return false;

    }

    public static void main(String [] args) {

    PriorityQueue app = new PriorityQueue();

    app.add(10, "STEVEN");

    app.add(1, "VANESSA");

    app.add(2, "CALU");

    app.add(3, "HANNA");

    while (app.hasNext()) {

    System.out.println((String)app.remove());

    }

    }

    }

    2008-05-31 11:06:47 補充:

    請到

    http://cid-8a3eb6847ead1ea2.skydrive.live.com/brow...

    下載

    Source(s): 自己, 自己
Still have questions? Get your answers by asking now.