开发者

Is casting an IEnumerable to an ArrayList O(N) or O(1)?

When I do this cast:

private IEnumerabl开发者_如何学Pythone objects;
ArrayList castedObjects = (ArrayList)objects;

Is this a "direct" cast, or the enumerable is converted into an ArrayList via an internal method (that presumably loops through all the elements)?


This is either a "direct" cast (if the underlying object is actually an instance of ArrayList), or you'll get an exception. No implicit creating of an ArrayList object is done "behind the scene".


This is a direct cast. It will only work if the object is an ArrayList already, for example:

IEnumerable objects = new ArrayList();
ArrayList castedObjects = (ArrayList)objects;

If the object is not an ArrayList but some other object that implements IEnumerable, the cast will fail.

You can create an ArrayList from an ICollection, for example:

ICollection objects = new string[] { "a", "b" };
ArrayList castedObjects = new ArrayList(objects);

This will loop through the collection and copy the items to the ArrayList, so it's an O(n) operation.


Generally you should not use the ArrayList class at all, but the generic List<T> class that offers strict typing.


It depends on what objects actually is. It is referenced as an IEnumerable, but its actual type may be anything that implements IEnumerable.

If the reference can be cast to an ArrayList (because it already is, or inherits from, ArrayList) then it is O(1). If it cannot, then you'll just get an exception.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜