views:

65

answers:

3

I need to migrate a code in java to javascript. In java, I am maintaining a hashmap with key = string and value = arraylist of objects

I need to implement the same in javascript:

this.hashMap = new Hash();
this.hashMapArrayList =[];
...
var hashMapDataSet = new HashMapDataSet(id1,name1,type1);
this.hashMapArrayList[0] = hashMapDataSet;
...
this.hashMap.set(fileName1, this.hashMapArrayList);

var hashMapDataSet1= new HashMapDataSet(id2,name2,type2);
this.hashMapArrayList[0] = hashMapDataSet1;
this.hashMap.set(fileName2, this.hashMapArrayList);

But when I try to get the properties for a specified key

this.hashMap.get(fileName1).getId()

I get the value= id2 which is the last id that was set for HashMapDataSet object.

I have tried to mimic getters and setters in javascript as specified in the following link: http://javascript.crockford.com/private.html

Here is the HashMapDataSet class

function HashMapDataSet(pId, pName, pType) {
var id = pId;
var name = pName;
var type = pType;

function getId1() {
return id;
}
function setId1(mId) {
id = mId;
}
....

this.getId = function () {
return getId1();
};

this.setId = function (id) {
setId1(id);
};

...
}

where getId1, setId1 are private methods and getId, setId are priviledged methods

I am new to javascript, so I am unable to correlate java object with javascript. Kindly help.

+1  A: 

I'm not quite sure what you're trying to do there, but in javascript you don't need all this java wiring, because the language has built-in maps and lists. Your snippet can look like this in js

this.hashMap = {};
this.hashMapArrayList =[];
...
this.hashMapArrayList.push({id: id1, name: name1, type: type1});
...
this.hashMap.fileName1 = this.hashMapArrayList;

this.hashMapArrayList.push({id: id2, name: name2, type: type2 });
this.hashMap.fileName2 = this.hashMapArrayList;
stereofrog
An Object isn't quite safe to use as a map in the general case. You can only have String keys, and using certain keys that clash with Object properties like `toString` will cause aggravating browser problems.
bobince
A: 

Hi,

The javascript-closure-loop problem is very common.

I would take a lot to: http://www.javascriptkata.com/2007/04/11/a-common-problem-with-the-powerful-javascript-closures/

Regards.

ATorras
A: 

for the class you needn't private functions, you can use directly privileged functions:

    function HashMapDataSet(pId, pName, pType)
    {
       var id = pId;
       var name = pName;
       var type = pType;

       this.getId = function ()
       {
          return id;
       };

       this.setId = function (pId)
       {
          id = pId;
       }
   }
xdevel2000