---
title: "Flex的Array和ArrayCollection"
author: "tomfish88"
date: "2011-03-24T15:29:51Z"
tags: ["ASP.net", "Dreamweaver", "Flash", "Flex", "搜索引擎"]
categories: ["编程语言"]
slug: "flex-array-arraycollection"
draft: false
lastmod: "2011-03-24T15:29:51Z"
id: 974109
url: "https://tomfish88.iteye.com/blog/974109"
---

1.array作为控件使用   
   FLEX3写法：   
      &lt;mx:Array id="barname"&gt;   
          &lt;mx:String&gt;Flash&lt;/mx:String&gt;   
          &lt;mx:String&gt;Director&lt;/mx:String&gt;   
          &lt;mx:String&gt;Dreamweaver&lt;/mx:String&gt;   
          &lt;mx:String&gt;ColdFusion&lt;/mx:String&gt;   
      &lt;/mx:Array&gt;   
   FLEX4写法：   
      &lt;fx:Array id="barname"&gt;   
          &lt;fx:String&gt;Flex&lt;/fx:String&gt;   
          &lt;fx:String&gt;Flash&lt;/fx:String&gt;   
          &lt;fx:String&gt;Dreamweaver&lt;/fx:String&gt;   
      &lt;/fx:Array&gt;   
   举例   
   &lt;mx:LinkBar  id="navigationBar" dataProvider="{barname}"/&gt;   
   &lt;mx:LinkBar  id="navigationBar" dataProvider="barname"/&gt;   
   注：写{}，则当barname数据的值修改后，linkbar的数据同步更新   
2.array在程序中使用   
   \[Bindable]   
   public var barname:Array=\["Flex","Flash","Dreamweaver"];   
   &lt;mx:LinkBar  id="navigationBar" dataProvider="{barname}"/&gt;   
   var barname:Array = new Array();   
   barname.push("Flex");   
   barname.push("Flash");   
   barname.push("Dreamweaver");   
   navigationBar.dataProvider = barname;   
3.array的排序   
   private var temp:Array = new Array(1,4,3,45,4,6,7,77,9);    
   function sortArray(numbers:Array):Array{          
      numbers.sort(Array.NUMERIC);    
      return numbers;    
   }   
4.ArrayCollection特点   
   ArrayCollection是flex中的数组集合类，它是很常用的，我们使用它时需要注意几个地方   
(1)事件监听   
    ArrayCollection可以为它注册一个集合改变的监听事件(CollectionEvent.COLLECTION\_CHANGE)，就是一旦 ArrayCollection数组改变就会触发Event，不是所有情况的改变都会触发改变事件，如果集合当中的对象属性没有被绑定，那么你改变它的对象值也是不会触发事件的，在这种情况下你也许可能需要去将对象的属性进行绑定或者通过itemUpdated方法去管理对象值改变,除非集合的长度改变了,事件才会被触发   
(2)对象删除   
    ArrayCollection的对象删除方法removeAll()，有这样一种情况，当你在过滤集合数据的时候，它并不会删除所有数据，而是删除全部过滤的数据，不符合过滤条件的数据就没被删除，依然还在source中   
(3)过滤函数   
    ArrayCollection有个filterFunction过滤函数，就是可能集合中你只需要显示其中某几个对象，你将会需要根据对象条件筛选对象，那么你可能会用过滤函数，过滤函数会将不符合条件的对象过滤出来，但是ArrayCollection有个source属性是不会变的，它是个数组，所有源数据全在里面，尽管你去过滤，所有对象都会一直存在其中   
(4)排序   
    ArrayCollection还有一个sort属性是用来排序的，你可以为其指定排序字段   
5.ArrayCollection在程序中使用   
(1)插入或删除   
   import mx.collections.ArrayCollection;    
   private var coll:ArrayCollection;    
    coll = new ArrayCollection(    
           [{name:"Martin Foo", age:25},    
            {name:"Joe Bar", age:15},    
            {name:"John Baz", age:23}]);    
    }   
   要插入元素，可使用addItemAt和addItem：    
   coll.addItemAt({name:"James Fez", age:40}, 0);   
   coll.addItem({name:"James Fez", age:40});   
(2)搜索   
   Sort 对象提供findItem 方法用于搜索这个ArrayCollection 中的所有元素。   
方法原型如下：   
   public function findItem(items:Array, values:Object, mode:String,   
returnInsertionIndex:Boolean = false, compareFunction:Function = null):int   
   Value 参数可以是包含属性和所需值的任何对象。   
   Mode 字符串可以是Sort.ANY\_INDEX\_MODE，表示返回任何匹配项索引，Sort.FIRST\_INDEX\_MODE 表示返回第一个匹配项索引，Sort.LAST\_INDEX\_MODE 表示返回最后一个匹配项索引。   
   returnInsertionIndex 参数表示如果该方法找不到由values 参数标识的项目，并且此参数为   
true，则findItem() 方法将返回这些值的插入点，也就是排序顺序中应插入此项目的。   
   compareFunction 设置用于查找该项目的比较运算符函数.   
举例   
   private function checkExistence():int {     
      var sort:Sort = new Sort();    
      return sort.findItem(coll.source,{name:nameTI.text, age:Number(ageTI.text)},  Sort.ANY\_INDEX\_MODE);    
   }   
(3)过滤   
   filterFunction 属性是由ListCollectionView 类定义，它是ArrayCollection 的父类。   
   当过滤器函数被传递给继承自ListCollectionView 的任何子类后，这里为ArrayCollection 对象，应用过滤器后必须调用refresh 方法   
   将原型为function(item:Object):Boolean 的函数传递给ArrayCollection 的filter 属性。如果返回true 表示值继续留在ArrayCollection，返回false 表示其值被移除。   
举例：   
  private function init():void {    
      coll = new ArrayCollection(\[{name:"Martin Foo", age:25},{name:"Joe Bar", age:15},name:"John Baz", age:23},{name:"Matt Baz", age:21}]);    
      coll.filterFunction = filterFunc;    
      coll.refresh();    
      for(var i:int = 0; i&lt;coll.length; i++) {    
          trace(coll.getItemAt(i).name);    
      }    
   }    
   private function filterFunc(value:Object):Object {    
      if(Number(value.age) &gt; 21) {    
          return true;    
      }    
      return false;    
   }   
(4)排序   
   首先要创建一个Sort，传递一个SortField 对象数组给fields 属性。这些SortField 对象包含的字符串正是每个ArrayCollection 元素将要用来排序的属性。如要对每个对象的age 属性进行排序，创建Sort 对象，传递SortField。   
    设置排序字段为age：   
    private function getOldest():void {    
       var sort:Sort = new Sort();    
       sort.fields = \[new SortField("age")];    
       coll.sort = sort;    
       coll.refresh();    
       trace(coll.getItemAt(0).age+" "+coll.getItemAt(0).name);    
    }    
    先按name升序排序，再按age降序排序   
    sort.fields = \[new SortField("name"),new SortField("age",true,true)];    
API说明：   
public function SortField(   
          name:String = null,    
          caseInsensitive:Boolean = false,    
          descending:Boolean = false,    
          numeric:Object = null)   
参数     
    name:String (default = null) — 此字段用来进行比较的属性的名称。如果该对象为简单类型，则传递 null。    
    caseInsensitive:Boolean (default = false) — 在对字符串进行排序时，指示比较运算符是否忽略值的大小写。   
    descending:Boolean (default = false) — 指示比较运算符是否按降序排列项目。     
    numeric:Object (default = null) — 指示比较运算符是否按编号而不按字母顺序比较排序项目。    
6.Array和ArrayCollection的比较   
Array的优点：   
   1)Array的性能优于ArrayCollection，从测试结果平均看来，ArrayCollection的效率是随着object的数目呈线性下降的，而Array则是体现了优异的效率，在object增加的情况下，基本上没有太大的变化。所以如果在你需要遍历所有元素的情况下(比如说物理引擎，3D引擎等)，Array是不错的选择   
     程序见附件1.   
   2)后台JavaBean也用的是数组\[]   
   3)for循环数组似乎比for each  ArrayConllection看起来更“傻瓜化”   
   4)给Array数组扩展长度，也可以变通实现，而且代价并不大   
ArrayCollection的优点：   
   1)ArrayCollection 实现接口 ICollectionView，在 Flex 的类定义内属于\[数据集]，他提供更强大的检索、过滤、排序、分类、更新监控等功能。类似的类还有 XMLListCollection   
   2)用 array 在作为 dataProvider 绑定于 control 之上，就无法获得控件的更新(实际上效果是可以得到更新的)，除非控件被重新绘制或者 data provider 被重新指定，而 Collection 则是将 array 的副本存储于 Collection 类的某个对象之中，其特点是 Collection 类本身就具备了确保数据同步的方法，例子如下（取自 adobe 内部工程师 training 示例，稍有改变）   
   3)对ArrayCollection中的对象进行增加删除更新操作时ArrayCollection会产生事件，可以通过collectionchange事件监听，所以在图表开发中都用ArrayCollection做数据源，一旦有更新，就会反映在图标上   
附件1：   
   &lt;?xml version="1.0" encoding="utf-8"?&gt;   
&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" frameRate="100" layout="vertical" horizontalAlign="center"&gt;   
    &lt;mx:Script&gt;   
        &lt;![CDATA[   
            import mx.collections.ArrayCollection;   
            \[Bindable]   
            private var ds:ArrayCollection;   
            private var array:Array;   
            private var ac:ArrayCollection;   
            public function loop(loopCount:uint):Object   
            {   
                array = null;   
                ac = null;   
                var begin:uint;   
                var end:uint;   
                var interval1:Number = 0;   
                var interval2:Number = 0;   
                var interval3:Number = 0;   
                var interval4:Number = 0;   
                var i:uint;   
                // for array, insert to array   
                i=0;   
                array= new Array();   
                begin = getTimer();   
                for (i;i&lt;loopCount;i++)   
                {   
                    array.push({test:"helllo"});   
                }   
                end = getTimer();   
                interval1 =  end - begin;   
                t1.text = interval1.toString()+" ms";   
                //loop the array   
                i=0;   
                begin = getTimer();   
                for (i;i&lt;array.length;i++)   
                {   
                    array\[i];   
                }   
                end = getTimer();   
                interval3 =  end - begin;   
                t3.text = interval3.toString()+" ms";   
                /// for ac, insert to array collection   
                i=0;   
                ac=  new ArrayCollection();   
                begin = getTimer();   
                for (i;i&lt;loopCount;i++)   
                {   
                    ac.addItem({test:"helllo"});   
                }   
                end = getTimer();   
                interval2 =  end - begin;   
                t2.text = interval2.toString()+ " ms";   
                //loop the array collection   
                i=0;   
                begin = getTimer();   
                for (i;i&lt;ac.length;i++)   
                {   
                    ac.getItemAt(i);   
                }   
                end = getTimer();   
                interval4 =  end - begin;   
                t4.text = interval4.toString()+ " ms";   
                return {ct:loopCount,   
                array\_insert:interval1,   
                ac\_insert:interval2,   
                array\_loop:interval3,   
                ac\_loop:interval4   
                };   
            }   
            private function autoLoop():void   
            {   
                ds=null;   
                ds = new ArrayCollection();   
                var i:uint=0;   
                for (i;i&lt;parseInt(count.text);i+=parseInt(count.text)&gt;100?parseInt(count.text)/10:1)   
                {   
                    ds.addItem(loop(i));   
                }   
            }   
            public function reset():void   
            {   
                t1.text ="0";   
                t2.text ="0";   
                t3.text = "0";   
                t4.text = "0";   
                count.text = "1000";   
                ds=null;   
                ds = new ArrayCollection();   
            }   
        ]]&gt;   
    &lt;/mx:Script&gt;   
    &lt;mx:ApplicationControlBar width="503"&gt;   
        &lt;mx:Label text="插入条数：" fontSize="12" color="#0B333C" fontWeight="bold"/&gt;   
        &lt;mx:TextInput width="98" text="1000" id="count"/&gt;   
        &lt;mx:Button id="startBtn0" label="Test" click="autoLoop()"/&gt;   
        &lt;mx:VRule height="15"/&gt;   
        &lt;mx:Button label="reset" click="reset()"/&gt;   
    &lt;/mx:ApplicationControlBar&gt;   
    &lt;mx:Panel width="500" height="480" layout="horizontal" id="testBed" title="Array 与Array Collection的性能比较" fontSize="11" fontWeight="normal"&gt;   
        &lt;mx:Canvas width="100%" height="100%" id="main" borderStyle="none" autoLayout="false"  horizontalScrollPolicy="off" fontSize="10"&gt;   
            &lt;mx:LineChart id="lc" x="8.5" y="133" width="463" height="306"  showDataTips="true" dataProvider="{ds}" &gt;   
                &lt;mx:horizontalAxis&gt;   
                    &lt;mx:CategoryAxis dataProvider="{ds}" categoryField="ct" title="插入Object数目"/&gt;   
                &lt;/mx:horizontalAxis&gt;   
                &lt;mx:verticalAxis&gt;   
                    &lt;mx:LinearAxis id="la" minimum="-1" title="响应时间（毫秒）"/&gt;   
                &lt;/mx:verticalAxis&gt;   
                &lt;mx:series&gt;   
                    &lt;mx:LineSeries displayName="array 插入耗时" yField="array\_insert" /&gt;   
                    &lt;mx:LineSeries displayName="arraycollection 插入耗时" yField="ac\_insert"/&gt;   
                    &lt;mx:LineSeries displayName="array 遍历耗时" yField="array\_loop"/&gt;   
                    &lt;mx:LineSeries displayName="arraycollection 遍历耗时" yField="ac\_loop"/&gt;   
                &lt;/mx:series&gt;   
            &lt;/mx:LineChart&gt;   
            &lt;mx:HBox x="10" y="0" width="460" height="134" horizontalAlign="left" verticalAlign="middle"&gt;   
                &lt;mx:Grid horizontalGap="1"  borderThickness="1" borderColor="#C6C6C6"  borderStyle="solid"&gt;   
                    &lt;mx:GridRow width="100%" height="100%"&gt;   
                        &lt;mx:GridItem width="86" height="100%"&gt;   
                            &lt;mx:Label text="毫秒(ms)" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%" fontSize="12"&gt;   
                            &lt;mx:Label text="Array"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%" fontSize="12"&gt;   
                            &lt;mx:Label text="ArrayCollection"/&gt;   
                        &lt;/mx:GridItem&gt;   
                    &lt;/mx:GridRow&gt;   
                    &lt;mx:GridRow width="100%" height="100%"&gt;   
                        &lt;mx:GridItem width="66" height="100%"&gt;   
                            &lt;mx:Label text="插入耗时" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%"&gt;   
                            &lt;mx:Text text="0" width="80" id="t1" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%"&gt;   
                            &lt;mx:Text text="0" id="t2" width="80" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                    &lt;/mx:GridRow&gt;   
                    &lt;mx:GridRow width="100%" height="100%"&gt;   
                        &lt;mx:GridItem width="100%" height="100%"&gt;   
                            &lt;mx:Label text="遍历耗时" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%" fontSize="12"&gt;   
                            &lt;mx:Text text="0" width="80" id="t3"/&gt;   
                        &lt;/mx:GridItem&gt;   
                        &lt;mx:GridItem width="100%" height="100%"&gt;   
                            &lt;mx:Text text="0" id="t4" width="80" fontSize="12"/&gt;   
                        &lt;/mx:GridItem&gt;   
                    &lt;/mx:GridRow&gt;   
                &lt;/mx:Grid&gt;   
                &lt;mx:VRule height="73" width="3"/&gt;   
                &lt;mx:Legend dataProvider="{lc}" width="100%" direction="vertical" fontSize="9" verticalGap="2" fontWeight="normal" fontStyle="normal" fontFamily="Verdana"/&gt;   
            &lt;/mx:HBox&gt;   
        &lt;/mx:Canvas&gt;   
    &lt;/mx:Panel&gt;   
    &lt;mx:LinkButton label="beherca" click="navigateToURL(new URLRequest('http://blog.beherca.com'),'\_blank')"/&gt;   
&lt;/mx:Application&gt;   
参考文献：   
   1.TonyLian. Array 和 ArrayCollection 区别. http://tonylian.iteye.com/blog/288964   
   2.凯文. Array 和ArrayCollection的性能比较. http://blog.beherca.com/logs/45628162.html   
   3.xldbk. Flex ArrayCollection几点注意. http://xldbk.iteye.com/blog/265064   
   4.Callan. Flex 集合(ArrayCollection). http://callan.iteye.com/blog/335551   
   5.hugo. Flex的ArrayCollection与Array的排序. http://www.hugo8.com/article.asp?id=744

**原文地址** [http://blog.chinaunix.net/u/21752/showart\_2086023.html](http://blog.chinaunix.net/u/21752/showart_2086023.html)