1.13. Dynamic Arrays: The ArrayList Collection Class

As the lines of text are read from the file, I prefer to store them rather than process them immediately. A string array would be the container of choice to do this, but the C# array is a fixed-size container. The required size varies with each text file that is opened, so the C# array is too inflexible.

The System.Collections namespace provides an ArrayList container class that grows dynamically as we either insert or delete elements. For example, here is our earlier read loop revised to add elements to the container:

using System.Collections;
private void readFile()
{
   ArrayList m_text = new ArrayList();
   string    text_line;

   while (( text_line = m_reader.ReadLine() ) != null )
   {
          if ( text_line.Length == 0 )
                 continue;

          // insert the line at the back of the container
          m_text.Add( text_line );
   }
   // let's see how many we actually added ...
   Console.WriteLine( "We inserted {0} lines", text.Count );
}

The simplest and most efficient way to insert a single element is to use the Add() function. It inserts the new element at the back of the list:

text.Add( text_line );

Count returns the number of elements held in the ArrayList object:

Console.WriteLine( "We inserted {0} lines", text.Count );

Just as we do for all reference types, we create an ArrayList object on the managed heap using the new expression:

ArrayList text = new ArrayList();

The elements of an ArrayList are stored in a chunk of contiguous memory. When that memory becomes full, a larger chunk of contiguous memory has to be allocated (usually twice the size) and the existing elements are copied into this new chunk. We call this chunk the capacity of the ArrayList object.

The capacity of an ArrayList represents the total number of elements that can be added before a new memory chunk needs to be allocated. The count of an ArrayList represents the number of elements currently stored within the ArrayList object. By default, an empty ArrayList object begins life with a capacity of 16 elements.

To override the default capacity, we pass in an alternative capacity when we create the ArrayList object—for example,

ArrayList text = new ArrayList( newCapacity );

where newCapacity represents a reasoned integer value. Capacity returns the current capacity of the ArrayList object:

Console.WriteLine( "Count {0} Capacity {1}",
                    text.Count, text.Capacity );

Once we've completed our element insertion, we can trim the capacity of the ArrayList to the actual element count using the TrimToSize() method:

text.TrimToSize();

Trimming an ArrayList object does not restrict our ability to insert additional elements. If we do, however, we once again increase the capacity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245