8.6. ArrayList Objects

The arrays that I have discussed thus far are called static arrays. This is because once you have set their element sizes, they cannot be changed. Indeed, you cannot use a static array until its dimension or dimensions have been determined. However, life isn't always that simple. Quite often you have a situation in which you know you need to store the data in an array, but don't have a clue how many elements you might need. For example, you might write a program that records the names and addresses of friends in an object called Friends. When you run the program you might need 50 array elements, but another person might only need 20 elements. The issue is: How do you decide how many elements to allocate for the array?

With static arrays, the usual solution is to settle for a worst-case design. A worst-case design is one in which you try to guess the largest reasonable value you will ever need for the size of the array and then set the dimension for the array to that size. This can be very inefficient because you will likely overestimate the required size for the array most of the time. The ArrayList object overcomes this limitations of static arrays. ArrayList objects have the effect of creating dynamic arrays for which you don't have to specify a size. Let's see how this works.

Try It Out: ArrayList Example

Let's write a simple program that enables you to add a person's name to a list. Because you have no idea how many names will be added by the user, ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.