简体   繁体   中英

Generics and ArrayList to implement a priority queue

I am stuck on an assignment which includes generics and ArrayList . The assignment is to implement a priority queue capable of holding objects of an arbitrary type T by defining a priority queue class that implements the queue with an ArrayList .

The method to be supported is Add(item, priority)

And depending on the priority remove() removes the highest item in the priority list.

I created the Generic Class with the type being T , declared private T data . Used multiple constructors to set data. Now I am stuck on how to use this class and Use ArrayList , as I am not sure you can add(string, integer) in an ArrayList let alone iterate through it.

Any tips and ideas on how to approach this homework will be greatly appreciated.

You simply need to wrap the data and its priority inside another object, only used internally by your PriorityQueue (just like a LinkedList uses nodes that wrap the data and a pointer to the next node).

So priorityQueue(T data, int priority) would end up being implemented as

Node node = new Node(data, priority);
// find the position where the node must be inserted
arrayList.add(position, node);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM