开发者

ArrayList cast to PriorityQueue + java

I am having this problem that I had used Arraylist in my entire program up till now and now I need its functioning to be that of priority queue too.

So I did the obvious that seemed to me and casted it like PriorityQueue z = (PriorityQueue) x where x was arraylist.

At runtime this gave an error that this is not possible.

Is there any simple way to make this work. I can't change entire array list as a priority queue since then I'll have to update all the functions used.....

Should I add item each time from arraylis开发者_开发问答t to a new priority queue or is there a better method...

Thanks a lot...


PriorityQueue pq = new PriorityQueue();
pq.addAll(x);


A priority queue has a lot of extra code associated with it to ensure that the items within the priority queue are ordered by priority. An array list has none of that code, so you can't just cast it into a priority queue.

Generally things can be upcast safely, but you're trying to downcast something here. You can't do it, as there's no assurance that the array list is ordered with any kind of priority. Nor are the underlying data structures implementing the two internally guaranteed to be the same.


There is no simple way. An ArrayList implements List interface, but not the Queue.

Creating a new queue from the list contents is probably simplest.

If you know the content is sorted by priority and you need to be really efficient, try wrapping it with a Queue class backed by your ArrayList if you need a queue-like object in one place, but are using Lists for good reasons elsewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜