java - Unexplained behavior while using hashmaps -


the stripped down program below works me when move hashval declaration (in bold) outside loop, program not run correctly. reasons why need inside loop when inserting in hashmap? found while thinking of potential optimizations after had gotten quick , sloppy implementation work. seems quick , sloppy implementation works not think should optimized version.

public class x {    public static void foo()    {       integer x1 = 0;       hashmap<integer, biginteger[]> map = new hashmap<integer, biginteger[]>();       int hashkey;       /* **biginteger[] hashval  = new biginteger[2];**  <-----does not run correctly        if keep hashval declaration here. (1) */       for(x1 = 0; x1 <= 1048576; x1++)       {         biginteger bx1 = biginteger.valueof(x1.intvalue());         **biginteger[] hashval  = new biginteger[2];** (2)         biginteger res;         /* lots , lots of big integer calculations , final result in res */         hashkey = res.hashcode();         /* store res , x1 in hashmap */         hashval[0] = res;         hashval[1] = biginteger.valueof(x1.intvalue());         map.put(hashkey, hashval);       }       integer x0;       for(x0 = 0; x0 <= 1048576; x0++)       {         /* lots of biginteger calculations generate res */          hashkey = res.hashcode();         **bignum = map.get(hashkey); <--------------never returns match if (1) above enabled instead of (2) !**     } } 

}

...because when hashval outside loop, gets created once , therefore inside loop continually push same biginteger[] map. in other words, every item in map ends being reference same biginteger[]. means whatever values put in biginteger[] during last time through loop each reference in map sees.

when create new biginteger[] inside loop, each time through loop hashval reference different biginteger[].


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -