Posts

Showing posts with the label collections

Retrieving items from Collection

Retrieving items from Collection I have a Collection c, which contains 3 items. I want to assign these 3 items to 3 different variables Collection<Object> c; var1 = firstItem; var2 = secondItem; var3 = thirdItem; How can I extract the elements of the collection? There is no effort from OP. – pvpkiran Jun 29 at 9:05 2 Answers 2 You can do it as following: Collection<Object> collection = ...; Iterator iterator = collection.iterator(); Object firstItem = iterator.next(); Object secondItem = iterator.next(); Object thirdItem = iterator.next(); Update: This option is fine only if you are sure that collection contains at least 3 items. Otherwise, you need to check whether iterator has next item (method hasNext ) before calli...

Change priorityQueue to max priorityqueue

Change priorityQueue to max priorityqueue I have priority queue in Java of Integers: PriorityQueue<Integer> pq= new PriorityQueue<Integer>(); When I call pq.poll() I get the minimum element. pq.poll() Question: how to change the code to get the maximum element? I think you should use the constructor that receives a comparator for that. Use the Collections.reverseOrder to obtain a reversed comparator. – Edwin Dalorzo Jun 12 '12 at 19:08 you need to pass a comparator. see stackoverflow.com/questions/683041/… – DarthVader Jun 12 '12 at 19:08 10 Answers 10 How about like this: PriorityQueue...