Understanding the Differences Between Object and Dictionary in ActionScript 3
The Dictionary class in ActionScript 3 (flash.utils.Dictionary) introduces a key distinction from the traditional Object class: it allows keys of any data type, not just strings.
When using Object instances as associative arrays, all keys are automatically converted to strings. This conversion can lead to unexpected behavior:
var collection:Object = new Object();
collection["identifier"] = 100; // String key "identifier"
collection[42] = 200; // Numeric key 42 becomes string "42"
collection[new Object()] = 300; // Object key becomes "[object Object]"
for (var key:String in collection) {
trace(key); // Outputs: [object Object], 42, identifier
trace(collection[key]); // Outputs: 300, 200, 100
}
This string conversion means that different objects used as keys will all resolve to the same string representation "[object Object]", causing them to reference the same value:
var firstKey:Object = new Object();
var secondKey:Object = new Object();
var data:Object = new Object();
data[firstKey] = "First Value"; // Actually sets data["[object Object]"]
data[secondKey] = "Second Value"; // Overwrites data["[object Object]"]
for (var item:String in data) {
trace(item); // Outputs: [object Object]
trace(data[item]); // Outputs: Second Value
}
The Dictionary class eliminates this limitation by preserving the actual object references as keys:
import flash.utils.Dictionary;
var keyA:Object = new Object();
var keyB:Object = new Object();
var mapping:Dictionary = new Dictionary();
mapping[keyA] = "Value A";
mapping[keyB] = "Value B";
for (var entry:* in mapping) {
trace(entry); // Outputs: [object Object], [object Object]
trace(mapping[entry]); // Outputs: Value A, Value B
}
Important considerations when working with Dictionary:
- Although trace output still shows "[object Object]" for object keys, these represent distinct object referances within the Dictionary.
- The iteration variable must be declared with the * type annotation since Dictionary keys can be of any data type.
Key differences between Object and Dictionayr:
- Object keys are always converted to strings via toString() if they are not already string values.
- Dictionary keys maintain object reference integrity and use strict equality (===) comparison without type coercion for key lookup operations.