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:

[code language=”java”]
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);
}
[/code]
The correct solution should look like this:

[code language=”java”]
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);
}
[/code]
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.

Leave a Reply

Your email address will not be published. Required fields are marked *