Iterating a Set
Monkey Forums/Monkey Programming/Iterating a Set
| ||
| Hi, I don't understand why, but when i do something like this my code crashes. Local mySet:Set<Object> = new Set<Object> For Local s:Object = eachin mySet 'do stuff here Next It works with lists but not with sets? |
| ||
| Sets are just wrappers around map objects, and because of the way they're implemented you need to extend the Set class for each kind of Set you want, and because it uses maps, you need to extend Map with a Compare method for your type as well. This isn't mentioned anywhere in the docs; I only worked it out by looking at the source. This should work:
Class Dude
Field name$
Method New(_name$)
name=_name
End
End
Class DudeMap<V> Extends Map<Dude,V>
Method Compare( lhs:Object,rhs:Object )
Local l:=Dude( lhs ).name
Local r:=Dude( rhs ).name
If l<r Return -1
Return l>r
End
End
Class DudeSet Extends Set<Dude>
Method New()
Super.New( New DudeMap<Object> )
End
End
Function Main()
Local s:=New DudeSet
s.Insert (New Dude("Jim"))
s.Insert (New Dude("Jemima"))
For Local d:=Eachin s
Print d.name
Next
End
|
| ||
| I see... Thank you warpy! This should definitely be in the official docs. |