Nice TWiki > Doc > CodeExamples > HashBeginnerExample (r1.1) TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Doc . { Changes | Index | Search | Go }
/* Please try the BeginnerExamples before the NoviceExamples
To compile:
   nicec --sourcepath=.. -a hash2.jar hash2
To run:
   java -jar hash2.jar 150
*/

void main(String[] args){
   var n = toSingleInt(args);
   let nKeys = 10000;

   HashMap<String,Cell> table1 = new HashMap(nKeys);
   HashMap<String,Cell> table2 = new HashMap();

   for (var i = 0; i <= nKeys; i++) 
      table1.put( "foo_" + toString(i), new Cell(value: i) );

   String key;
   int v1;        
   ?Cell c2;      // c2 = table2.get(key) can be null 

   while (n-- > 0) {
      Iterator<Map.Entry<String, Cell>> item = table1.entrySet().iterator();
      while(item.hasNext()) {
         Map.Entry<String, Cell> e = item.next();
         key = e.getKey();
         v1 = e.getValue().value;                       
         if ( (c2 = table2.get(key)) != null)
            c2.value += v1;   
         else 
            table2.put(key, new Cell(value: v1) );
      }
   }
   print( toString( table1.get("foo_1") )); print(" ");
   print( toString( table1.get("foo_9999") )); print(" ");
   print( toString( table2.get("foo_1") )); print(" ");
   println( toString( table2.get("foo_9999") )); 
}


class Cell { int value; }


String toString(?Cell c) {
   if (c==null) return "null"; else return toString(c.value);
}


int toSingleInt(String[] s){
   try { return Integer.parseInt(s[0]); }
   catch (Exception e){ return 1; } }



/* Notes - language
Compare with Java at the "Win32 Language Shootout"

   var n = toSingleInt(args);
Declare variable n, the compiler will infer the variable type
from the return type of the package function toSingleInt(String[] s)

   let nKeys = 10000;
Declare constant nKeys, the compiler will infer the constant type
from the literal value.

   HashMap<String,Cell> table1 = new HashMap(nKeys);
Declare and initialize table1 with type parameter <String,Cell>
HashMap<String,Cell> keys are type String and values are type Cell

   class Cell { int value; }
Define a new class Cell, with a single field. Using a Cell
in the HashMap allows entries to be updated without using
put(key,value).

   String key;
Declare variable key with type String (that excludes null values)

   ?Cell c2;
Declare variable c2 as an Option Type with type Cell or null.

   String toString(?Cell c) {
Define a package function

   int toSingleInt(String[] s){
Define a package function

*/

-- IsaacGouy? - 26 Aug 2003

Topic HashBeginnerExample . { Edit | Attach | Ref-By | Printable | Diffs | r1.6 | > | r1.5 | > | r1.4 | More }
Revision r1.1 - 27 Aug 2003 - 00:01 GMT - IsaacGouy
Parents: WebHome > CodeExamples
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.