# 請問關於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:

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:

Rating

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) {

}

//從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();

while (app.hasNext()) {

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

}

}

}

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

請到