Programming: Silly mistakes

This post will capture all the silly mistakes I’ve done so that I won’t repeat them again.

 

  1. While trying to add objects to the object’s list I had issue where all the elements(aka objects) were actually last object that I’ve added.

Code snippet with error:

List<String> characterImage = new ArrayList<String>();
for (int i = 0; i < numberOfCharacters; i++) {
    Character ch = new Character(characterImage);
    for (int j = 0; j < numberOfRows; j++) {
       characterImage.add(sc.next());
 }
 characters.add(ch);
 }

The correct solution should look like this:

List;String> characterImage;
 for (int i = 0; i < numberOfCharacters; i++) {
    characterImage = new ArrayList<String>();
    Character ch = new Character(characterImage);
    for (int j = 0; j < numberOfRows; j++) {
       characterImage.add(sc.next());
 }
 characters.add(ch);
 }

Obvious error, was that characterImage list haven’t been re-created for new object of Character, meaning we’ve been adding same list latest elements to the Character object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s