Forum Moderators: open
I've been looking all over for examples on how to do this, but haven't found anything useful.
I have created a class, something like this:
Class MyClass
...
class definitions
.....
End MyClass
I need to create instances of this class, but at any time when the page runs, I don't know ahead of time how many instances I will need. How do I dynamically create instances of this class (objects) and then be able to reference each instance?
Normally, I would do:
set myObject = new myClass
But is there such a thing as:
for i = 1 to 5
set myObject & i = new myClass
next
For a better idea conceptually of what I need, say I have a shopping cart object, with properties like totalNumberOfItems, subTotal, etc. I also have product objects with properties of productID, price, weight, etc.
Everytime a product is added into the shopping cart, I want to create a new product object, but how do I name and/or reference that object on the fly? That is what I don't quite get.
TIA
ArrayList myArrayList = new ArrayList(); for (int i = 0; i < 5; i++) {
myArrayList.add(new MyClass());
} If you want to read the arraylist, use count to get how many objects are in it:
MyClass tempObject; for (int i = 0; i < myArrayList.Count; i++) {
tempObject = (MyClass)myArrayList[i];
} Note that you have to do a cast since the arraylist stores everything just as "objects", that way, you can store different types of objects in the same arraylist (which isn't possible with a normal array).
Hope this helps
//ZS
Here is what I did in VBscript:
Class Package
....
define my class
.....
End Class
' Dynamic array
Dim arrPackages()
' array Index
Dim packageIndex
packageIndex = 0
' Every time I need to create a new object I do this:
Redim Preserve arrPackages(packageIndex)
set arrPackages(packageIndex) = New Package
' Iterate packageIndex
packageIndex = packageIndex + 1
Woo-hoo!
cococure
HTH
<edit>
Oh, just saw shopping cart. Unlikely you'll need to dim 20 at a time!
</edit>