开发者

ArrayList.Add - adds just references?

开发者 https://www.devze.com 2023-02-05 06:42 出处:网络
I a开发者_开发问答m unable to find on MSDN so I am trying here again :) When adding element, its boxed and the reference to new object is added to the collection (if it is value type) or if the elemen

I a开发者_开发问答m unable to find on MSDN so I am trying here again :) When adding element, its boxed and the reference to new object is added to the collection (if it is value type) or if the element is reference type, just reference is added to arraylist. Is that correct?

EDIT: So it contains just instances of Object class where each one references the value on the heap<


That is correct.

In real code, however, you should use generic List<T>s instead of ArrayLists.


Yes it is correct.

ArrayList is not generic (it is from Fx 1.1) and has members like

void Add(System.Object item)  { ... }

So anytime you call Add(x), x has to be converted to a System.Object typed reference. A trivial up-cast for any object reference but Boxing is needed for a value type.

And to join the majority here: You should (almost) never use it anymore. It's only for code that begun before 2005 and maybe for some very rare situation where you want to store mixed types.


Yes. That is correct.

List<> works differently, however.


Yes it is correct but you should not use ArrayList anyway and stick to generics.


Yes it is, just add a reference.

This is called shallow copy reference. In your case, you must implement a deep copy so you can create a new object and copy your value to it.

0

精彩评论

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