Why does Flex's ArrayCollection's Contain method look at memory reference?

那年仲夏 提交于 2020-01-01 05:36:08

问题


When using .contains() on an ArrayCollection in Flex, it will always look at the memory reference. It does not appear to look at an .equals() method or .toString() method or anything overridable. Instead, I need to loop through the ArrayCollection every time and check each individual item until I find what I'm looking for.

Does anyone know why Flex/ActionScript was made this way? Why not provide a way from people to use the contains() method the way they want?


回答1:


Couldn't you just extend ArrayCollection and override the contains() method? Alternatively you can paste the source for ArrayCollection into an "mx/collections" package in your project and modify the source; this "monkey-patching technique" will override the behavior throughout your entire project. However I would be extremely cautious about changing ArrayCollection in that manner: since it's used all over the place in the Flex APIs there is a good chance you'll start breaking other components in the framework.




回答2:


The contains() method searches by reference, correct (I believe even for primitives), so if you're trying to find a string or an int in an ArrayCollection, you'll have to do the searching yourself, by some variation of looping or searching. I don't think any of us could tell you why there isn't, say, an optional parameter on that method indicating whether to search by ref or by val, though; so it goes, as they say.

But I'd definitely warn you off monkey-patching the framework code -- that's just asking for trouble. :)




回答3:


Well, it seems like the ArrayCollection doesn't actually look directly at memory, but only as a last resort. It will attempt to find a Unique ID (UID) for the object. If the UID doesn't exist, it will create one for it using the UIDUtil.as.

You can get around this whole default UID stuff by having your object implement the IUID interface and providing your own UID for the object. The ArrayCollection will look at the UID you provide it.




回答4:


I would suggest a simple:

in_array($haystack, $arrayCollection->toArray());


来源:https://stackoverflow.com/questions/389846/why-does-flexs-arraycollections-contain-method-look-at-memory-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!