ArrayLists vs Lists?

Monkey Forums/Monkey Programming/ArrayLists vs Lists?

SLotman(Posted 2013) [#1]
Guys, I need some help. I wrote some code to deal with all chars in my game, which is basically:
Class CharList Extends List<AnimChars>
	Method Compare:Int(a:AnimChars, b:AnimChars)
		If a.sprite.y > b.sprite.y Then Return 1
		If a.sprite.y = b.sprite.y Then 
		   If a.sprite.x = b.sprite.x Then Return 0
		   If a.sprite.x > b.sprite.x Then Return 1
		End If
		Return -1
	End Method
End Class


Then I just create a CharList, and render it:
charlist.Sort(True)
Local ac:AnimChars
For ac = Eachin charlist
  ac.draw()
next


As long as I'm using List, everything works fine.
But if I change charlist into a ArrayList, then this happens:

(Look at the red circles, sprites are not sorted by their Y/X value)

It appears that ArrayList can't be sorted? But then why charlist.Sort(True) still compiles?


SLotman(Posted 2013) [#2]
Oh, I've got it! I had to change my CharList class to:
Class CharList Extends IComparator

Then create a ArrayList and set it's comparator to Charlist!
(Also, had the parameters changed on 'Compare' to o1:Object and o2:Object and in the function I had to cast them to AnimChars)

I just wonder why it's so different from 'regular' List...?


Nobuyuki(Posted 2013) [#3]
expandibility, presumably. Without having worked with ArrayLists in diddy I can only assume that IComparator exists for a future where we have multiple sorting methods and containers, all standardized to interoperate with each other. You say using an interface like IComparator that "Hey, my class can be compared by a generic sorting method", then the sorting method, agnostic to your classes' contents, goes "okay!".

The magic involved is when you're re-using crap; Unlike List<T>, you don't have to extend the container itself for each specific class just to be able to sort something in an instance of that class. Furthermore, multiple sorting methods could be used by having different comparator methods, so you can sort ascending, descending, or some other collated or hybrid method.

Late note: I took a peek at the source of diddy's comparator.monkey and notice that IComparator is actually an Abstract, not an Interface, so not everything I say here may apply.


SLotman(Posted 2013) [#4]
I'm not using diddy - monkey has that built in...


Nobuyuki(Posted 2013) [#5]
Monkey has ArrayLists now? I wasn't aware.


AdamRedwoods(Posted 2013) [#6]
Monkey has ArrayLists now?

??? not in lists, maybe in stacks, but otherwise you need to roll your own.


Markus(Posted 2013) [#7]
(Look at the red circles, sprites are not sorted by their Y/X value)

you should sort by depth/z