How do I get a PriorityQueue to sort on what I want it to sort on?
Also, is there a difference between the offer and add methods?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the constructor overload which takes a
Comparator<? super E> comparatorand pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you’re not sure. (It’s pretty straightforward though.)As has been said elsewhere:
offerandaddare just different interface method implementations. In the JDK source I’ve got,addcallsoffer. Althoughaddandofferhave potentially different behaviour in general due to the ability forofferto indicate that the value can’t be added due to size limitations, this difference is irrelevant inPriorityQueuewhich is unbounded.Here’s an example of a priority queue sorting by string length:
Here is the output: