Java: A Array Mystery

By Xah Lee. Date:

In the following code's HashMap, the values are supposed to be different for each entry. But they are all the same, why? (answer lies few screens down)

import java.util.*;
public class hasharray {
     static HashMap gen (int n) {
         HashMap result = new HashMap(100);
         int[] v= new int[2];
         for (int j=1; j <= n; j++) {
             for (int i=1; i < j; i++) {
                 v[0]=i;v[1]=j;
                 result.put(i+ ","+j, v);
             }
         }
         return result;
     }

     static HashMap prin (HashMap pairings) {
         int[] k= new int[2];
         for (Iterator it=pairings.values().iterator(); it.hasNext(); ){
             k = (int[]) it.next();
             System.out.println(k[0]+","+k[1]);
         }
         return pairings;
     }

     public static void main(String[] args) {
         HashMap result = new HashMap(100);
         result = gen(5);
         System.out.println(result.toString());
         prin(result);
         System.out.println(result.toString());
     }
}
↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

Answer

Here's the answer to the above question.

In the code that adds the hash values:

v[0]=i;v[1]=j;
result.put(i+ ","+j, v);

each iteration the object v is added to the HashMap result. (in Java, with technicality, arrays are objects.) In each iteration the array's values are changed, however, The result seems to contain all identical arrays.

The intended program should have the array declaration inside the loop like this:

int[] v= new int[2];
v[0]=i;v[1]=j;
result.put(i+ ","+j, v);

or the simpler syntax irregularity

int[] v= {i,j};
result.put(i+ ","+j, v);

so that in each iteration a new object is added as the value to the hash key.

(thanks to people in Yahoo and Sun Microsystem's Java forums for answer to the question.)

The behavior Java the lang exhibited above, is that in most imperative languages, they represent some underlying models based on hardware, as opposed to a mathematical interpretation of the code. So in the above, v represent some mystic “object” thingie behind the scenes. Even though ostensibly its value is changed and placed into the list in each iteration, but that's not what it seems.