ArrayList in Map

Monkey Forums/Monkey Programming/ArrayList in Map

Zwer99(Posted 2012) [#1]
Hello!

Why isn't following code working?

Class ObjectBank Extends StringMap<ArrayList<SIObject>>
	Public
		Method UpdateObjects:Void(screen:String)
			For Local obj:SIObject = EachIn Self.Get(screen)
				obj.Update()
			Next
		End
		
		Method DrawObjects:Void(screen:String)
			For Local obj:SIObject = EachIn Self.Get(screen)
				obj.Draw()
			Next
		End
		
		Method addObject:Void(obj:SIObject, screen:String)
			ArrayList<SIObject>(Self.Get(screen)).AddLast(obj)
		End
		
		Method getObjectsByScreen:ArrayList<SIObject>(screen:String)
			Return Self.Get(screen)
		End
End


If I try to call "addObject()", then this error appear:

Monkey Runtime Error : TypeError: Cannot convert 'this.m_Get(t_screen)' to object



Samah(Posted 2012) [#2]
You can't cast to generic classes.


Zwer99(Posted 2012) [#3]
Ahaaa! Thank you for the hint! I didn't know that :)

I solved it like this:

Class SIObjectArrayList
	Public
		Field list:ArrayList<SIObject>
		
		Method New()
			Self.list = New ArrayList<SIObject>()
		End
End

Class ObjectBank Extends StringMap<SIObjectArrayList>
	Public
		Method UpdateObjects:Void(screen:String)
			For Local obj:SIObject = EachIn SIObjectArrayList(Self.Get(screen)).list
				obj.Update()
			Next
		End
		
		Method DrawObjects:Void(screen:String)
			For Local obj:SIObject = EachIn SIObjectArrayList(Self.Get(screen)).list
				obj.Draw()
			Next
		End
		
		Method addObject:Void(obj:SIObject, screen:String)
			If Not Self.Contains(screen)
				Self.Insert(screen, New SIObjectArrayList())
			EndIf
			SIObjectArrayList(Self.Get(screen)).list.AddLast(obj)
		End
		
		Method getObjectsByScreen:ArrayList<SIObject>(screen:String)
			Return SIObjectArrayList(Self.Get(screen)).list
		End
End


Is there a better solution?


marksibly(Posted 2012) [#4]
Hi,

It should work - what target are you building for?

You shouldn't really need the cast anyway, the 'Get' method will return an object of the correct type.


Samah(Posted 2012) [#5]
Since when can you cast to a generic? I remember asking this ages ago and your response was "TODO". That's pretty spiffy. :)

http://www.monkeycoder.co.nz/Community/posts.php?topic=523#4023