views:

90

answers:

1

Hi all,

if wrote the following code and do not understand why the trace returns "false":

function (with trace):

        import mx.controls.Alert;
        import mx.collections.ArrayCollection;

        public function runTest():void {
            var unique1:MyUniqueObject = new MyUniqueObject();
            unique1.id = 1;

            var unique2:MyUniqueObject = new MyUniqueObject();
            unique2.id = 2;

            var sameUniqueAsUnique1:MyUniqueObject = new MyUniqueObject();
            sameUniqueAsUnique1.id = 1;

            var collection:ArrayCollection = new ArrayCollection();
            collection.addItem(unique1);
            collection.addItem(unique2);

            trace(collection.contains(sameUniqueAsUnique1));
        }

MyUniqueObject-Class:

package
{
    import mx.core.IUID;

    [Bindable]
    public class MyUniqueObject implements IUID
    {
        public var id:int;

        public function get uid():String {
            return "MyUniqueObject." + id;
        }

        public function set uid(uid:String):void {
            //nothing to do here...
        }
    }
}

Any Ideas?

Cowabunga!

+1  A: 

why should it? the implementation uses ==, and actually even === in your case.

also, the accessors are never called.

contains is a method of ListCollectionView and causes the following:

  1. call to ListCollectionView::getItemIndex
  2. sort == null && filterFunction == null, thus:
  3. IList::getItemIndex

For ArrayCollection ListCollectionView::list is an ArrayList implementing getItemIndex as ArrayUtil.getItemIndex(item, source); which in fact uses strict comparison between the item and and the source array entries.

If you want the call to evaluate to true, you will need to provide your own implementation of IList. Subclassing ArrayList and overriding getItemIndex will do the trick although I am not certain it won't break some other functionality.

greetz

back2dos

back2dos
I thought this should work because I read this:http://stackoverflow.com/questions/389846/why-does-flexs-arraycollections-contain-method-look-at-memory-reference/709777#709777
cowabunga1984
@cowabunga1984: I am using flex 3.4 and all I can say is, it doesn't work. your accessors are **never** even called. you can verify that by simply putting in traces. also, if you look at the implementation, you'll see that it just won't work that way. this is possibly different in Flex 4. still, I find it hard to believe Adobe introduced this behaviour, since it can break a lot of code in a very subtle matter at a point where you just wouldn't expect it.
back2dos