Referring to the previous answer to the question about SO, there is a method used called TestForNull. This was my original code before I was told that I can make it more efficient:
My source code:
for (int i = 0; i < temp.length; i++) { if (map.containsKey(temp[i])) map.put(temp[i], map.get(temp[i]) + 1); else map.put(temp[i], 1);
In this passage, I take three views of the map. I was told that this can only be done in one search, so I decided to find the answer in SO and found the related answer and changed my code to look like this:
Modified Code:
for (int i = 0; i < temp.length; i++) { Integer value = map.get(temp[i]); if (value != null) map.put(temp[i], value + 1); else map.put(temp[i], 1); }
Even if it seems better, it looks like two looks at me, not one. I was wondering if there is an implementation that uses only one, and if it can be done without using third-party libraries. If this helps, I use HashMap for my program.
source share