Array versus Collections

  • Thread starter Thread starter Matt
  • Start date Start date
M

Matt

What is the major differences between array and collection? For example,
ArrayList. When to use which? I think array is static container, but
collection is dynamic container. The drawback of array is to define the size
in declaration, but not in collection.

Please advise...
 
Matt,

I'll assume you have NOT read the MSDN documentation on Array, ArrayList and
a Collection. Which you should!

As for when to use which, it is more of a style or speed issue.

Something to keep in mind is that a collection is nothing more than array
that has a whole lot of code wrapped around it to manage adding/expanding
the array. This is why speed can be an issue.

Now since most applications need to be more maintainable than fast, I try to
use the following guide lines when deciding which to use.
If you know the number of objects to be stored use an array. If not, use a
collection.
If after creating an array a process must add an unknown number of objects
to it use a collection.

In my experiance designing reusable objects, It is not a good practice to
allow objects to return/expose Arrays or ArrayLists. This is because it
never fails that I have to end up and add code to all my methods to make
sure that each list object is the type that I'm expecting. What I do is to
create a class that inherats from CollectionBase so that only objects of
expected types are allowed to be added. By doing this it forces a "Strong
Typed" structure, which is the been found to be the easiest to
code(opinion).

Hope this helps.
 
Back
Top