ArrayLists vs Lists?
Monkey Forums/Monkey Programming/ArrayLists vs Lists?
| ||
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? |
| ||
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...? |
| ||
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. |
| ||
I'm not using diddy - monkey has that built in... |
| ||
Monkey has ArrayLists now? I wasn't aware. |
| ||
Monkey has ArrayLists now? ??? not in lists, maybe in stacks, but otherwise you need to roll your own. |
| ||
(Look at the red circles, sprites are not sorted by their Y/X value) you should sort by depth/z |