Map that uses objects as keys?
Monkey Forums/Monkey Programming/Map that uses objects as keys?
| ||
Basically I want to try and have a Map that uses objects as a key, for example a predefined Class. The value would be a List. Something like: Map < myClassA, List< myClassB >> Is this possible or am I trying to achieve the impossible? |
| ||
well some more fiddling and tinkering and this appears to work but I have no idea how or why.... |
| ||
In my opinion it works because your object has an "id" member which is a number value. This is how map can work by using numbered values. If "id" were an actual object like Image, it wouldn't work. |
| ||
Well thats what I initially thought, but im not using the id value in the compare method... |
| ||
You're right, but I couldn't compile your version without converting Compare to: Method Compare : Int( a : Object, b : Object ) And then if I use Image Classes for keys in NodeObject, it works. This is very important and interesting find. Good job! my thought is I wonder if the Object type is allowed to be compared by pointer... |
| ||
my thought is I wonder if the Object type is allowed to be compared by pointer... Yea that was what I was wondering as well... |
| ||
Hi, > And then if I use Image Classes for keys in NodeObject, it works. This is very important and interesting find. Good job! This is a bug - Monkey should not be letting you use < and > with objects! The C++ targets support object 'pointer' comparisons, but none of the others do. To use objects as keys, you'll need to implement some way to compare keys, eg: Class Key Public Method New() id=cnt cnt+=1 End Private Field id Global cnt End Class KeyMap<T> Extends Map<Key,T> Method Compare( x:Key,y:Key ) Return x.id-y.id End End |
| ||
Thank you for clearing that up Mark, I was concerned with the use of < and > on objects. It felt wrong! |
| ||
Doh! |