I’m working with relatively complex data structures with javascript. I have a hashtable with a String as key and an Array (or ArrayList) as a value which itself contains a number of built-in lists. I’m trying to pull the Array from the hashtable, add something to it, and store it back in the hashtable.
I think it makes sense to use a temporary Array for this, so I did something like this:
measureListTemp = measures[currMeasureID] as Array; //pull existing measure out of hashtable
measureListTemp.Add(currNote); //add to measure
measures[currMeasureID] = measureListTemp; //put list back in hastable
But what seems to be happening is the actual Array, not the contents, are being stored in the hashtable, so anytime I write to the “temporary” Array, it changes everything in the hashtable. How do I properly go about adding things to an Array inside a hashtable. I tried using an ArrayList and putting a shallow copy via Clone into the hashtable, but that didn’t work either.
So if I get this correctly, you don’t want to change the reference that’s being stored in the hashtable, you just want to change the values within the array?
Can’t you just remove this line:
measures[currMeasureID] = measureListTemp; //put list back in hastable
You don’t need to put it back into the hashtable. You get a reference, then use the reference to add to the referenced array. The hashtable is still pointed at the same reference so it’ll see the updated array.
Thank you, you've also given me the right idea; I marked Louis' answer as correct because it was a little closer to what I needed to implement.
It sounds like you’ve got the same array in your hashtable over and over. If that’s so, just add different arrays.
Instead of:
var ht : Hashtable = new Hashtable();
var arr: Array = new Array();
ht.Add(1, arr);
arr.Clear(); arr.Add(2);
ht.Add(2, arr);
You need to make a new array for each entry, not just clear the same one.
ht.Add(1, arr);
arr = new Array(); arr.Add(2);
ht.Add(2, arr);
You can also copy an Array easily with new Array(arr), which creates a copy of arr in a new spot in memory.
Thank you, I had to rework some more of my code, but this idea worked for me. I'm familiar with python where arrays and dictionaries are just data (I think), so passing them back and forth just moves the information. But I'm slowly getting my head around the more object-oriented stuff.
Just so you know, it's better to avoid the Array class (or ArrayList) and Hashtable. Use generic List and Dictionary instead; they are faster/better. http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F
– Eric5h5Good to know, thanks, I'll keep that in mind if I have time to optimize my code better.
– stwert