what's the difference...

  • Thread starter Thread starter Bad_Kid
  • Start date Start date
ArrayList can be changed at any time (add or remove items). Arrays are
static and cannot be changed. They must be copied to be modified.
 
An ArrayList is better when you have heterogenous collections, or you need
dynamic list-like behavior. If you know that you have 5 instances of Apple,
use an array.

An instance of ArrayList can be sized dynamically:
ArrayList arrList = new ArrayList();
while(true)
arrList.Add(new Dollar());

A native C# array (which is an instance of System.Array) has a fixed size.

An ArrayList has elements of type object, which enables you to add any
element to your array (for good or evil):
arrList.Add(new Apple());
arrList.Add(new Orange());
arrList.Add(new JessicaSimpson());

A native C# array has elements of a specific type:
Apple[] arr = new Apple[2];
arr[0] = new Apple();
arr[1] = new Orange(); // compiler error
 
Hi Bad_Kid,

Bad_Kid said:
arraylist / array ???
what is better for what?

In addition to Peter's comments, ArrayLists are always generic
containers, whereas arrays can be type-specific (you can't put a string
value into an array of int, for example). The other thing to know is that
value types (ints, longs, enums, structs, etc.) get "boxed" going into an
ArrayList and "unboxed" coming out of an ArrayList. A lot of boxing and
unboxing can have negative performance implications.

Regards,
Daniel
 
An ArrayList is better when you have heterogenous collections, or you need
dynamic list-like behavior. If you know that you have 5 instances of Apple,
use an array.

A native C# array has elements of a specific type:
Apple[] arr = new Apple[2];
arr[0] = new Apple();
arr[1] = new Orange(); // compiler error

However, to get *exactly* the same behaviour as ArrayList in this
respect, just use object:

object[] arr = new object[2];

arr[0] = new Apple();
arr[1] = new Orange();

Dynamic sizing is (IME) the only real reason to use ArrayList - but
then it's incredibly useful, of course!
 
Back
Top