would like to know the difference on following methods, namely why two identical (identical by its logic) methods do not return the same expected result:
Method: create a Map of Character and List of Words:
void setMapping(List<String> words) { Map<Character, List<String>> wordsByLetter = new HashMap<>(); for (String word : words) { char letter = word.toLowerCase().charAt(0); List<String> ref = wordsByLetter.get(letter); if (ref == null) { ref = new ArrayList<>(); wordsByLetter.put(letter, ref); } ref.add(word); } }
So in this case we make a reference to List of Strings called 'ref' and it will be updated each time we call method 'add' on it. Unfortunately, the same approach doesn't work with the second one:
2th Method: count all appearances:
void countCategories(List<String> categories) {
Map<String, Integer> mapper = new HashMap<>();
for (String category : categories) {
//need object Integer either to provide reference to it and to check whether it is a null
Integer counter = mapper.get(category);
if (counter == null) {
counter = 0;
//DOESN'T WORK THE SAME WAY:
//mapper.put(category, counter);
}
counter++;
mapper.put(category, counter);
}
}
So, my question is, why the second method doesn't work the same way as the first one, namely, why we cannot update counter in the particular Collection through object reference?