Results 1 to 18 of 18
Like Tree1Likes
  • 1 Post By Tolls

Thread: Error: java.util.ConcurrentModificationException. Any help to find out why?

  1. #1
    Manddd is offline Member
    Join Date
    Mar 2015
    Posts
    23
    Rep Power
    0

    Default Error: java.util.ConcurrentModificationException. Any help to find out why?

    hey guys, so I'm using a for each loop to go through an arrayList, however it is throwing an error at me: ( this is the error)
    Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unk nown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at assignment4.Inventory.add(Inventory.java:40)
    at assignment4.TestInventory.main(TestInventory.java: 13)
    This my Inventory class:
    Java Code:
    package assignment4;
    import java.util.ArrayList;
    import java.io.*;
    
    public class Inventory {
    	
    	private ArrayList<movie> movieList;
    	
    	public Inventory() {
    		
    	
    		BufferedReader br = null;
    		this.movieList = new ArrayList<movie>();
    	 
    	 try {
    			 br = new BufferedReader(new FileReader("movieBase.txt"));
    			  String str;
    			   while (( str= br.readLine()) != null) {
    				  String[] arraySplit = str.split("-");
    				  String title = arraySplit[0];
    				  int year = Integer.parseInt(arraySplit[1]);
    				  int length = Integer.parseInt(arraySplit[2]);
    				  double rating = Double.parseDouble(arraySplit[3]);
    				  movie newMovie = new movie(title,year,length,rating);
    			      movieList.add(newMovie);
    				}
    			br.close();
    	 	}catch (FileNotFoundException e){
    	 		System.err.println(e);
    	 	}catch (IOException e){
    		    System.out.println(e);
    		   }
    	 	
    	}
    	
    	  public void add(String movieName, int year, int duration, double rating) {
    		   movie newMovie = new movie(movieName, year, duration,rating);
    		  while(movieList.iterator().hasNext()){
    		   for(movie m: movieList){
    				   if(newMovie == m){
    					   int x = newMovie.getQuantity();
    					   newMovie.setQuantity(x+1);
    					   movieList.add(newMovie);
    				   }
    				   else
    					   movieList.add(newMovie); 
    			   }
    		  }
    		  }
    
    		  public void remove(String movieName, int year) {
    		  int i = 0;
    		  while(movieList.iterator().hasNext()){
    		   for(movie m: movieList){
    			     if(m.getTitle() == movieName && m.getYearReleased() == year){
    			    	if(m.getQuantity() >1){
    			    		i++;
    			    		int x = m.getQuantity();
    			    		m.setQuantity(x-1);
    			    		
    			    	 }else if(m.getQuantity() == 1){
    			    		movieList.remove(m);
    			    		i++;
    			    	}
    			      }
    		     }
    		   } 
    		   if(i>0){
    			     System.out.println("No movie have been found.\nSo nothing will be deleted");
    		   }
    		  }
    		  
    		  
    		  public String toString(){
    			  String str = " ";
    			  for(movie m: movieList){
    				  str += m.toString();
    		        }
    			  return str;
    		  }
    		
    		
    	}
    and this is my main class:
    Java Code:
    package assignment4;
    
    public class TestInventory {
    	 
    	 public static void main (String[] args) {
    	  
    	  Inventory movieList = new Inventory ();
    	  
    	  //TODO:
    	  //Read in the input file and populate the movieList
    	  
    	  //these movies should be added to the inventory
    	  movieList.add("Bears", 2014, 120,  3.5);
    	  movieList.add("Star Wars - A New Hope", 1977, 110, 3.8);
    	  movieList.add("Casablanca", 1942, 130,3.9);
    	  movieList.add("Duck Soup", 1933, 130, 3.75);
    	  
    	  System.out.println(movieList.toString());
    	  
    	  //the count of Casablanca should increase
    	  movieList.add("Casablanca", 1942, 140, 3.9);
    	  
    	  System.out.println(movieList.toString());
    	  
    	  //this movie should not be added since it has invalid year
    	  movieList.add("Bears", 2050, 150, 3.5);
    	  
    	  System.out.println(movieList.toString());
    	  
    	  //this movie is not in the inventory, so nothing should change
    	  //and the program should continue
    	  movieList.remove("The Nightmare Before Christmas", 1993);
    	  
    	  System.out.println(movieList.toString());
    	  
    	  //count should decrease, but Duck Soup should remain in the inventory
    	  //since there were two copies before
    	  movieList.remove("Duck Soup", 1933);
    	  
    	  System.out.println(movieList.toString());
    	 }
    	}

  2. #2
    Join Date
    Aug 2015
    Location
    Northern California
    Posts
    31
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Where is movie defined?

  3. #3
    Manddd is offline Member
    Join Date
    Mar 2015
    Posts
    23
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    sorry, didn't think it would be needed as i thought thep roblem was with the inventory class:

    Java Code:
     package assignment4;
    
    public class movie { 
    	 //Attributes :
    	 /*title (String) title of the movie
    	 yearReleased (int) year that the movie was released (and positive integer between 1870 and 2015)
    	 rating (double) user rating (any positive floating point number between 0.0 and 4.0)
    	 quantity (int) number of discs at the distribution center (a positive integer)
    	 duration (int) duration of the movie in minutes ( a positive integer)*/
    	 
    	 private String title;
    	 private int yearReleased;
    	 private double rating;
    	 private int quantity;
    	 private int duration;
    	 
    	 //Constructor:
    	 /*
    	  * tis constructor takes 4 paramater and sets the quantity of a movie to 1
    	  */
    	 public movie(String Title, int YearReleased, int Duration, double Rating){
    	  try{
    	   this.title = Title;
    	   this.yearReleased = YearReleased;
    	   this.rating = Rating;
    	   this.duration = Duration;
    	   this.quantity = 1;
    	   }catch(IllegalArgumentException e){
    	    System.out.println();    
    	   }
    	 }
    	 
    	 //accessors
    	 public String getTitle(){
    	  return this.title;
    	 }
    	 
    	 public int getYearReleased(){
    	  return this.yearReleased;
    	 }
    	 
    	 public int getDuration(){
    	  return this.duration;
    	 }
    	 
    	 public double getRating(){
    	  return this.rating;
    	 }
    	 
    	 public int  getQuantity(){
    	  return this.quantity;
    	 }
    	 
    	 
    	 //mutators
    	  public void setTitle(String newTitle){
    	   title = newTitle;
    	  }
    	  
    	  public void setYearReleased(int newYearReleased){
    	   yearReleased = newYearReleased;
    	  }
    	  
    	  public void setDuration(int newDuration){
    	   duration = newDuration;
    	  }
    	  
    	  public void setRating(double newRating){
    	   rating = newRating;
    	  }
    	  /*
    	   * if quantity is more than 0, the quantity will be set to the one passed to the mutator.
    	   * However, if it is an invalid input, it will automatically set it to 0;
    	   */
    	  public void setQuantity(int newQuantity){
    	   if(newQuantity >=0)
    	    quantity = newQuantity;
    	   else{
    	    System.out.println("Input is invalid. Quantity will be set to 0.");
    	    quantity = 0;
    	   }
    	  }
    	  
    	  //toString format:
    	  public String toString(){
    	   String some = String.format("%12s %6s rating : %6s %6s #in stock : %6s",title,yearReleased,rating, duration, quantity);
    	   return some;
    	  }
    	}

  4. #4
    trcooke is offline Tim Cooke
    Join Date
    Jul 2014
    Location
    Belfast
    Posts
    101
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    The problem is in here:
    Java Code:
            for (movie m : movieList) {
                if (newMovie == m) {
                    int x = newMovie.getQuantity();
                    newMovie.setQuantity(x + 1);
                    movieList.add(newMovie);
                } else
                    movieList.add(newMovie);
            }
    You cannot add to a list while iterating over it.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Two more things in that one snippet.

    1) when you increase a quantity of an existing movie, do you really want to add newMovie to the list anyway?
    2) movie is an object, doing an == comparison generally is not the way you check if a new object you are adding has the same properties (such as a name) as an existing object

    And when I take one extra line of that snippet:

    Java Code:
    while(movieList.iterator().hasNext()){ // as soon as there is at least one movie, this will always be true so this is an endless loop
               for(movie m: movieList){
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    You'll have the same issue with the remove method, though in that case you can use the Iterator itself to do the removing.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Join Date
    Aug 2015
    Location
    Northern California
    Posts
    31
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    movie is not a movieList from what I see that's why I brought it up and now that I have tested it I see I do get an error in Eclipse Mars.

    edit: removed the rest of this actually I haven't looked that closely at your code
    Last edited by devMichaelSmith; 08-12-2015 at 09:14 AM.

  8. #8
    Manddd is offline Member
    Join Date
    Mar 2015
    Posts
    23
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    So, wait, that is something I haven't heard of. The foreach loop is an iteration? isn't that the same as going through a for loop and adding something to an array? How would I possibly add an item while going over my arrayList?

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    You only want to add a newMovie if that movie isn't already in your list, so the logic is:
    Java Code:
    for each movie in list
        does this movie match the new one?
        if so increment and exit
        otherwise continue looping
    if new movie not added (this will need a flag set in the loop)
        add new movie
    The adding of the new movie is done outside the loop.
    gimbal2 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    trcooke is offline Tim Cooke
    Join Date
    Jul 2014
    Location
    Belfast
    Posts
    101
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Alternate logic that avoids any explicit looping could be
    Java Code:
    if (movieList contains movie) {
      get movie from movieList
      increment qty on movie
    } else {
      add movie to movieList
    }

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Note how that is not only pseudo code, it is also just spelling it out in plain English. The latter is a useful thing to do when you get stuck; just explain it to yourself in English. If you have illogical code, you'll get a story which does not match what you want to achieve.

    In any case, I'd like to make a note about the earlier comment: "How would I possibly add an item while going over my arrayList? " - that is something you only need to do when you want to insert a movie somewhere in a specific position in the list. But as you say yourself, you only want to add an item which you can just do to the end of the list.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    26

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Tim, isn't the second line redundant?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  13. #13
    trcooke is offline Tim Cooke
    Join Date
    Jul 2014
    Location
    Belfast
    Posts
    101
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    It is not. I think my terrible naming convention is confusing things. I'll try again
    Java Code:
    if (movieList contains movieToAdd) {
      listItemMovie = get movieToAdd from movieList
      increment qty on listItemMovie
    } else {
      add movieToAdd to movieList
    }
    I'm taking advantage of Java's list mutability (yuk) by directly modifying the item in the list.

  14. #14
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Do note that the code does not contains any hint of overriding equals() (objects are still being compared with == ) , and your pseudo code does depend on the programmer understanding how that mechanism works.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    To be fair, so does mine.
    I was saving that up for the next problem ("why does it not find the movie in the list?").
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Quote Originally Posted by Tolls View Post
    To be fair, so does mine.
    Perhaps that was in your brain, but the way you wrote it down can work just as well without an equals().

    In any case I'm shutting up now, too many people picking at the same things is just chaos.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  17. #17
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    26

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Quote Originally Posted by trcooke View Post
    It is not.
    OK I see it now. A duplicate, not repeat, insertion. Although that does imply to me that a Map<Movie, Integer> would be more appropriate.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  18. #18
    trcooke is offline Tim Cooke
    Join Date
    Jul 2014
    Location
    Belfast
    Posts
    101
    Rep Power
    0

    Default Re: Error: java.util.ConcurrentModificationException. Any help to find out why?

    Agreed. A Map<Movie, Integer> would be a better data structure for keeping stock levels of Movies.

Similar Threads

  1. Replies: 29
    Last Post: 03-09-2014, 08:40 PM
  2. ConcurrentModificationException error in for loop
    By Sutured in forum New To Java
    Replies: 3
    Last Post: 03-18-2013, 10:13 PM
  3. java.util.ConcurrentModificationException
    By user92 in forum New To Java
    Replies: 2
    Last Post: 11-02-2012, 05:31 PM
  4. java.util.ConcurrentModificationException
    By mharsijamel in forum New To Java
    Replies: 1
    Last Post: 11-02-2011, 02:40 PM
  5. Replies: 19
    Last Post: 08-28-2009, 12:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •