Map that uses objects as keys?

Monkey Forums/Monkey Programming/Map that uses objects as keys?

NoOdle(Posted 2011) [#1]
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?


NoOdle(Posted 2011) [#2]
well some more fiddling and tinkering and this appears to work but I have no idea how or why....




AdamRedwoods(Posted 2011) [#3]
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.


NoOdle(Posted 2011) [#4]
Well thats what I initially thought, but im not using the id value in the compare method...


AdamRedwoods(Posted 2011) [#5]
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...


NoOdle(Posted 2011) [#6]
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...


marksibly(Posted 2011) [#7]
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



NoOdle(Posted 2011) [#8]
Thank you for clearing that up Mark, I was concerned with the use of < and > on objects. It felt wrong!


AdamRedwoods(Posted 2011) [#9]
Doh!