开发者

How to create an ArrayCollection of Objects?

开发者 https://www.devze.com 2023-03-22 23:28 出处:网络
I new to flex, I have a class shown below: public class Items extends Object { pu开发者_如何学JAVAblic function Items(){

I new to flex, I have a class shown below:

public class Items extends Object
{
    pu开发者_如何学JAVAblic function Items(){
        super();
    }

    public var name:String;
    public var count:int;
}

How do I create an ArrayCollection of type Items?

Thanks.


var item1:Items = new Items();
item1.name = "Name1";
item1.count = 5;

var item2:Items = new Items();
item2.name = "Name2";
item2.count = 7;

var items:ArrayCollection = new ArrayCollection([item1, item2]);

Another way:

var items:ArrayCollection = new ArrayCollection();

var item1:Items = new Items();
item1.name = "Name1";
item1.count = 5;
items.addItem(item1);

var item2:Items = new Items();
item2.name = "Name2";
item2.count = 7;
items.addItem(item2);


You can also create these in mxml (inside if you're using flex 4)

<s:ArrayCollection id="theCollection">
    <namespace:Items name="name 1" count="5" />
    <namespace:Items name="name 2" count="6" />
    <namespace:Items name="name 3" count="7" />
    <namespace:Items name="name 4" count="8" />
</s:ArrayCollection>

Then reference the array by its id.


Somewhere in your code:

var ac : ArrayCollection = new ArrayCollection();
var newItem : Items = new Items();
newItem.name = 'some value';
newItem.count = 1;
ac.addItem(newItem);
newItem = new Items();
newItem.name = 'some other value';
newItem.count = 2;
ac.addItem(newItem);
newItem = new Items();
newItem.name = 'Yet another value';
newItem.count = 3;
ac.addItem(newItem);
...

It may be worth nothing that ArrayCollections are not typed in the same way that a Vector may be, so there is nothing you can do to force all items in your collection to be of the Items type. [Unless you extend ArrayCollection somehow and override the addItem / addItemAt methods to throw errors if the type is wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消