views:

181

answers:

2

I'd like my associative array indexed by Point (or, in general, an Object) that has a semantic equality. Unfortunately

var p:Point = new Point(1, 1);
var q:Point = new Point(1, 1);

var dict:Dictionary = new Dictionary();
dict[p] = 5;
trace(dict[p]); // => 5
trace(dict[q]); // => undefined

because

trace(p===q); // => false

Is there any way to tell Dictionary how to order its keys, or is there a different class to use for this type of thing?

A: 

Apparently if you use Object, it seems to work as intended:

var p:Point = new Point(1, 1);
var q:Point = new Point(1, 1);
var r:Point = new Point(1, 2);

var dict:Object = new Object();
dict[p] = 5;
trace(dict[p]); // => 5
trace(dict[q]); // => 5
trace(dict[r]); // => undefined
Jesse Beder
i haven't tried this, it's just a hunch, but are you *sure* this works? i suspect it might do a string conversion on p before using it as an index, so ALL points will collide.
grapefrukt
I believe Object's keys are just strings, so any non-String object you use as a key will be converted to a string. Object's toString() method returns the same thing regardless of its contents, so this most likely would not work.
Herms
It appears to. See edit
Jesse Beder
What I mean is, it *does* seem to work correctly
Jesse Beder
aha. it works because points have a nice toString function that outputs the two values (x=1, y=2) so i guess it will work the way you want, though i'm not sure it's the prettiest of solutions ;)
grapefrukt
So what *would* be the prettiest of solutions?
Jesse Beder
A: 

A Dictionary will place objects in different bins, even if they are "equal". If the two objects used as keys result in a collision on insertion, the Dictionary will simply use the next available bin to place the second object, because, as you said, p!==q. But using Object (which is still, in essence, a map) is different, it only checks if p.equals(q).

geowa4
Actually, the `Object` must *not* check `p==q`, since in this case, it's false! (but `p.equals(q)` is true)
Jesse Beder
could've sworn it returned true for me. meh, no biggie; shouldn't be using `==` anyway.
geowa4