of class, and also to see our athletes compete. There is time to talk about their interests and plans for the future. It was also encouraging for me to hear that at least one other of the AP CSA students is at least considering a major in Computer Science. I'm not quite sure why, but I always count it as a win when I hear of a student deciding to pursue a major in CS which I enjoyed and hope that these students find a rewarding career programming, as I did. It was a good week...until Thursday when I was reminded again that we all (teachers included) have many opportunities to learn from mistakes and none of us has all of the answers.
When Things Go Wrong
On Thursday, students had a studio day and were finishing off their final labs and reviewing for theupcoming test on ArrayList, references, and OOP. One of the students was stuck on a lab trying to load elements into an ArrayList. The loop he had written looked for an item in an empty list. If the item was not found, it would be created and added to the list. If the item was found, the counter in the item was increased. However, since the list was empty the loop checking for the item was never executed. I pointed this out and we decided to add an if statement before the loop and check for an empty list and then add the first item. Problem solved!
Then we ran the code and received a ConcurrentModificationException. I was stumped. This was a single threaded program, multithreaded programming was not something we would be covering, so the error made no sense. We looked at the Javadoc for the error and saw that this exception could also occur if an item in a List is changed while iterating through the List. OK, that explained the error but not how to fix it.
We Learn
After struggling with the error for some time, I finally went back to my desk and looked at thesolution for the lab. I had not noticed the get...() method immediately below the load...() method. The get() method was already implemented and just waiting to be used. After updating the code, it worked fine. We spent some time reasoning through why the solution worked and the original code could potentially cause problems -- changing a list item while iterating through the same list could essentially pull the rug out from under yourself.
This proved to be a great learning experience for all of use.
- We learned about the list iteration and changing list items.
- We learned about the ConcurrentModificationException
- My students learned that even when you have been coding for a long time, you can still run into things that stump you.
- And I learned that although I like not looking at the solutions to the labs provided with my AP CSA curriculum, I had best do this from now on!
There is an important lesson for me -- wanting to always have the answer is not always the best way for students to learn. A struggle is good!