qaispak qaispak - 1 year ago 72
Java Question

Why does one of this loop not work for incrementing a hash table?

So I have two loops. They use a key on a hashtable. If there is nothing in that key, store 1. If there is something store whatever there is plus 1.

for(int i=0; i<nums1.length; i++) {
Integer count = nums_hash.get(i);
if (count == null) {
nums_hash.put(nums1[i], 1);
else {
nums_hash.put(nums1[i], count+1);

This first one does not work but the following works perfectly fine:

for(int i = 0; i < nums1.length; i++)
if(nums_hash.containsKey(nums1[i])) {

else nums_hash.put(nums1[i], 1);

I would like to understand an explanation for this.

Answer Source

Your second line of code should be

Integer count = nums_hash.get(nums1[i]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download