Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: What's wrong with my method?

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default What's wrong with my method?

     
    /**
         * Remove from the club's collection all members who
         * joined in the given month, and return them stored
         * in a seperate collection object.
         * @param month The month of the membership.
         * @param year The year of the membership.
         * @return The members who joined in the given month.
         */
        public ArrayList<Membership> purge(int month)
        {
            ArrayList<Membership> purgeMembers = new ArrayList<Membership>();
            if(month < 1 || month > 12) {
                System.out.println("Error: Month " + month + 
                    " out of range. Must be in the range 1 ... 12");
            }
            else {
                for(Membership membership : members) {
                    if(membership.getMonth() == month) {
                        members.remove(members.indexOf(membership));
                        purgeMembers.add(membership);
                    }
                }
     
            }
            return purgeMembers;
        }

    When I call this method with a valid parameter, it throws a java.util.ConcurrentModificationException.
    I read in the API documentation for the ArrayList class what it is, but I dont fully understand it and I dont know how to get over it. Can I use the Collections.synchronizedList method here and if yes how I do it? Can someone explain me a little bit about this staff? Or should I just separate these threads so that thay dont access the arrayList at the same time and achieve my goal like that? Nevertheless it is an opportunity to learn about something that I accidentally came across..


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: What's wrong with my method?

    Most likely because you are modifying the size of the members list while looping it with an iterator.
    Try this instead:
    for(int i=0;i<members.size();i++) {
    	Membership membership = members.get(i);
    	if(membership.getMonth() == month) {
    		members.remove(i);
    		i--;
    		purgeMembers.add(membership);
            }
    }

    The short-hand for loop for(Membership membership : members) uses an Iterator (Iterator (Java Platform SE 7 )). Iterators do not like you modifying the size of the list while iterating. The for loop which I suggested above uses indexes instead of an iterator, so adjusting the size (as well as adjusting the index position) is not a problem.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. The Following 2 Users Say Thank You to aussiemcgr For This Useful Post:

    bihlas (June 28th, 2014), GregBrannon (June 27th, 2014)

  4. #3
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: What's wrong with my method?

    You get this exception because you are modifying (add / remove) a collection while you are iterating over it at the same time.
    The standard iterators are written in a way to always throw these exceptions if the underlying collection has been changed after they have been created.

    There are several solutions to your problem. First, you could use the Iterators "remove" method to safely remove an element from a collection while you are iterating over it.
    Other then that you could use a second, temporary collection in which you remember which elements you want to delete after your iteration, then you delete them at the apropriate time.

  5. The Following 2 Users Say Thank You to Cornix For This Useful Post:

    bihlas (June 28th, 2014), GregBrannon (June 27th, 2014)

  6. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: What's wrong with my method?

    Or start at the end of the list and go towards the first item. Then there is no need to change the index (i--);
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following 2 Users Say Thank You to Norm For This Useful Post:

    bihlas (June 28th, 2014), GregBrannon (June 27th, 2014)

  8. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: What's wrong with my method?

    I never thought about that. Clever, lol.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #6
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: What's wrong with my method?

    Just to expand on this a bit more in case you're still unsure of the documentation at ArrayList (Java Platform SE 7 ), there are two possible causes of ConcurrentModificationException:
    1. "If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally [...] (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)"
    2. "If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods", i.e., the "fail-fast behaviour"

    #1 only occurs if you have 2 or more threads using (and structurally modifying) the ArrayList at the same time. The use of "List list = Collections.synchronizedList(new ArrayList(...));" is applicable for this scenario. (If you're not sure what I mean by "thread", see Lesson: Concurrency and Processes and Threads.)

    #2 occurs even when you have just one thread using the ArrayList. The word "concurrent" in the exception in this case does not refer to concurrent access of the ArrayList by multiple threads, but to performing structural modification after having created the iterator for the ArrayList. Collections.synchronizedList() will not help in this scenario.

    In your case, it is #2, as the good members above have helpfully posted.

  10. The Following User Says Thank You to jashburn For This Useful Post:

    GregBrannon (June 28th, 2014)

Similar Threads

  1. Replies: 4
    Last Post: March 6th, 2014, 05:14 PM
  2. Remove at index method for singly linked list... what's wrong?
    By EDale in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 27th, 2013, 09:12 PM
  3. I can't get my last method to work! What am I doing wrong?
    By deejeridoozy in forum What's Wrong With My Code?
    Replies: 6
    Last Post: September 18th, 2013, 07:39 PM
  4. What is wrong with this method?
    By CrizR in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 27th, 2013, 03:50 PM
  5. can't figure whats wrong with my add method?? help!
    By b094mph in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 8th, 2011, 05:00 PM