wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Collections" Watch "Regarding Collections" New topic
Author

Regarding Collections

Prasad Maddipatla
Greenhorn

Joined: Apr 20, 2007
Posts: 24
Hi ,

import java.util.*;

public class PQ
{
public static void main(String[] args)
{
PriorityQueue<String> pq = new PriorityQueue<String>();

pq.add("carrot");
pq.add("apple");
pq.add("banana");

for(String s q)
pq.offer(s);

System.out.println("--->"+pq.poll()+"--->"+pq.peek());
}
}


I am getting RuntimeException ... can any one help me out.
Prasad Maddipatla
Greenhorn

Joined: Apr 20, 2007
Posts: 24
hi friends its

for(String s : pq)
Gaurav Joshi
Greenhorn

Joined: Mar 08, 2008
Posts: 18
Hi Prasad Maddipatla



Line 1 uses Enhanced for loop, alternative for Iterator, implicitly iterators are used, hence the above for loop line can be substituted for

Now the first iteration of for loop will execute smoothly and apple will be added, but as implicit iterator excutes and performs s = it.next() , Concurrent Modification Run Time Exception is Thrown
Hence if Iterator used, addition an deletion should always be done through Iterator
Khushbu Ghodasara
Ranch Hand

Joined: May 09, 2007
Posts: 35
Originally posted by Prasad Maddipatla:

for(String s : pq)


this is the line which is causing the runtime exception.

here you are getting ConcurrentModificationException
That is because you are concurrently iterating a Collection and modifying the same collection. here is the excerpt taken from J2SE 5.0 API,

http://java.sun.com/j2se/1.5.0/docs/api/java/util/ConcurrentModificationException.html

public class ConcurrentModificationException
extends RuntimeException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.


hth.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding Collections