Single list of any type
Monkey Forums/Monkey Beginners/Single list of any type
| ||
Not for any specific program but I was wondering if this was possible? Say I had a list(or any other type of dimensioned structure) and I wanted to dump multiple unrelated objects in it. Then at a later point parse through the list and process each object differently, dependant on their class type. The only way I can see for this to work is by using interfaces or super-classes, both of which require messing with the object structure? |
| ||
Yes, generally speaking those are the two main ways to handle running a method on disparate objects in a list. The advantage to using an interface is that you don't have to always inherit from the superclass. Define an interface with a processing method requirement, set the list to the type of your interface, and for each object type that goes in the list, define that processing method within the object class's definition. This requires minimal refactoring of your existing object structure - just implement the interface and add the required method to each class you want to use. |
| ||
You can do it as Object list:List<Object> but will be forced to cast every object before using them. |
| ||
Like Jesse mentioned, make the list a general Object list. Then inside each object, have a field thta determines the type of the object. When you iterate through the list, cast the object to one which represents the actual class of the object and you can go from there. |
| ||
Ah, that clarifies my options by quite a bit, thank you all. If speed is of a precedent then use interfaces but if you don't mind the casting hit, then my life could be much simpler by going down the "of type" Object route. |
| ||
I still believe using an Interface or Abstract superclass is a better practice depending on your needs -- casting from Object is very ugly. Edit: And the reason is because when you start needing to use the mystery Objects in your list, you need to perform a voodoo downcast and pray to the computer gods that you don't end up hosing your program at runtime |
| ||
Yeah, the thing about casting from objects is that either you need some kind of reflection or else a way of knowing what each object is when you access it from the list If your objects all contain a 'type' field, you are already close to effectively having an interface or base class. |
| ||
Casting objects on HTML5 and Android is pretty slow, so it's something I will probably avoid for that reason alone too. |
| ||
[bbcode] Interface IProcess Method Process : Void() End Interface '// As many classes as you need can implement IProcess, allowing different control over each type in the list Class Item Implements IProcess Method Process : Void() '// Process here! End Method End Class '// Store all IProcess classes, each having a unique process method Global processList : List< IProcess > [/bbcode] Thats how I would start at least, allows a lot of freedom with little costs. |