Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList vs List<object>

I saw this reply from Jon on Initialize generic object with unknown type:

If you want a single collection to contain multiple unrelated types of values, however, you will have to use List<object>

I'm not comparing ArrayList vs List<>, but ArrayList vs List<object>, as both will be exposing elements of type object. What would be the benefit of using either one in this case?

EDIT: It's no concern for type safety here, since both class is exposing object as its item. One still needs to cast from object to the desired type. I'm more interested in anything other than type safety.

EDIT: Thanks Marc Gravell and Sean for the answer. Sorry, I can only pick 1 as answer, so I'll up vote both.

like image 963
faulty Avatar asked Dec 24 '08 09:12

faulty


People also ask

Should I use ArrayList or List?

There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second.

What is the difference between List and object?

In practical terms there is no difference, they both compile down to the exact same code. List<Object> though is showing that you have thought about what will go in the list and know it could be anything, whereas List on its own shows nothing.

Can ArrayList store objects?

The Java collection classes, including ArrayList, have one major constraint: they can only store pointers to objects, not primitives. So an ArrayList can store pointers to String objects or Color objects, but an ArrayList cannot store a collection of primitives like int or double.


1 Answers

You'll be able to use the LINQ extension methods directly with List<object>, but not with ArrayList, unless you inject a Cast<object>() / OfType<object> (thanks to IEnumerable<object> vs IEnumerable). That's worth quite a bit, even if you don't need type safety etc.

The speed will be about the same; structs will still be boxed, etc - so there isn't much else to tell them apart. Except that I tend to see ArrayList as "oops, somebody is writing legacy code again..." ;-p

like image 83
Marc Gravell Avatar answered Oct 11 '22 15:10

Marc Gravell