Other .NET Collection Classes


The System::Collections and System::Collections::Specialized namespaces contain a number of very useful collection classes that can be used in C++ programs. Some of the most commonly used ones are listed in the following table. A couple of them will be examined later in more detail to give you an idea of how they work.

Class

Description

ArrayList

A dynamically growable array

Hashtable

A collection that stores elements by key

Queue

Stores a list of elements and accesses them in the same order they were stored

SortedList

A collection that extends Hashtable, allowing you to retrieve elements by index as well as by key

Stack

Accesses a list of elements from the top only

StringCollection

Stores a list of strings and retrieves them by index (defined in System::Collections::Specialized)

StringDictionary

A Hashtable with the key strongly typed to be a String (defined in System::Collections::Specialized)

The ArrayList Class

The ArrayList class, defined in the System::Collections namespace, is a dynamically growable (and shrinkable) array. By default, instances of this class are resizable and writable, but the class provides two static methods that let you create read-only and fixed-size ArrayLists.

The following exercise shows you how to create an ArrayList and manipulate it.

  1. Open Visual Studio, and create a new Visual C++ Console Application (.NET) project named ArrayList.

  2. Open the ArrayList.cpp source file, and add the following line immediately after the using namespace System; line:

    using namespace System::Collections;

    The ArrayList class is defined in the System::Collections namespace. By inserting a using directive, you can use the name without having to fully qualify it every time.

  3. Add some code to the _tmain function:

    int _tmain() { Console::WriteLine(S"ArrayList Demo"); // Create a default ArrayList ArrayList* pal = new ArrayList(); // Look at the count and capacity Console::WriteLine(S"Capacity={0}", __box(pal->Capacity)); Console::WriteLine(S"Count={0}", __box(pal->Count)); // Adjust the capacity pal->set_Capacity(10); Console::WriteLine(S"Capacity={0}", __box(pal->Capacity)); // Add some elements pal->Add(__box(0)); pal->Add(__box(2)); pal->Add(__box(3)); pal->Insert(1, __box(1)); Console::WriteLine(S"Count is now {0}", __box(pal->Count)); return 0; } 

    The default ArrayList constructor creates an empty ArrayList. The next two lines use the Capacity and Count properties to print the current capacity of the ArrayList and a count of how many objects it currently contains. You’ll find if you run this code that the count is 0—not surprising because we haven’t added anything yet—and that the capacity is 16. The default capacity of an ArrayList is 16, which means that you can add up to 16 items before the object has to go back to the operating system for more memory. An alternative constructor lets you specify a different initial capacity, as shown here:

     // Create an ArrayList with a capacity of ten elements ArrayList* pal = new ArrayList(10);

    If you exceed the capacity when adding elements, it will automatically be doubled. If your array is too large, you can reduce its capacity to match the actual number of elements stored by calling TrimToSize. You can also reset the capacity of the ArrayList at any time by using its Capacity property.

    ArrayList doesn’t contain any elements until you add some using the Add or Insert functions. Add adds a new item to the end of the list, while Insert takes a zero-based index and inserts a new item at that position. Note once again that to add an int to the ArrayList, I have to box it to obtain an Object pointer.

    Note

    Because ArrayList stores any object that inherits from Object— and that means all .NET types—you can store mixed types in a single ArrayList.

  4. You can print out the contents of the ArrayList in two ways: explicitly, by using the get_Item function, or by using an enumerator. Add this code to print the contents using the get_Item method:

    for (int i=0; i<pal->Count; i++) Console::WriteLine(S"Item({0}) = {1}", __box(i), pal->get_Item(i));

    The get_Item method returns a reference to the item at a given index in the collection, and it will throw an ArgumentOutOfRangeException if the argument is less than 0 or greater than the current count. You can obtain and use an enumerator in exactly the same way as you did in the “Enumerators” section earlier in the chapter.

  5. The syntax for removing items from the ArrayList is similar to that used for retrieving them.

    // Remove item at index 2 pal->RemoveAt(2);

    If you want to remove more than one element, the RemoveRange function takes a starting index and a number of elements to remove. In addition, if you have stored a pointer to an object in the collection, you can use the Remove function, which will search the ArrayList and remove the first occurrence.

Other ArrayList Operations

The ArrayList class implements the same interfaces as the System::Array class discussed earlier in the chapter, which means that it provides much of the same functionality.

  • The IList interface provides the Add, Clear, Contains, IndexOf, Insert, Remove, and RemoveAt methods, plus the Item, IsFixedSize, and IsReadOnly properties.

  • The ICollection interface provides the CopyTo method, plus the Count, IsSynchronized, and SyncRoot properties.

  • The IEnumerable interface provides the GetEnumerator method.

  • The ICloneable interface provides the Clone method.

These interfaces are used to specify common functionality for the collection classes. Once you know how the interface methods work, it becomes easier to use other collection classes.

The SortedList Class

The SortedList class, also defined in the System::Collections namespace, represents a collection of keys and values. A SortedList is very similar to a Hashtable, which also maintains key/value pairs, but the SortedList maintains its data in sorted key order and allows you to access items by index as well as by key. In this section, you’ll see how the SortedList class works, and you’ll be able to apply what you learn to the Hashtable class as well.

Note

Because of the need to maintain a sort order, operations on a SortedList are usually slower than on an equivalent Hashtable, so only use a SortedList if you need access to elements by index as well as key.

SortedList sorts its entries two ways:

  • The objects stored in the SortedList can implement the IComparable interface with its CompareTo method. All the value types, such as number and string classes, implement this interface, and you should implement it on any other user-defined types whose values can be ordered.

  • An external comparer object can be provided, which implements the IComparer interface with its Compare method.

The following exercise shows you how to create a SortedList and manipulate it. As an example, suppose you wanted to maintain a list of employees’ names together with their phone extensions. A SortedList would work well in this case, using the name as the key and the extension as the value.

  1. Open Visual Studio, and create a new Visual C++ Console Application (.NET) project named SortedList.

  2. Open the SortedList.cpp source file, and add the following line immediately after the using namespace System; line:

    using namespace System::Collections;

    The SortedList class is defined in the System::Collections namespace, and by inserting a using directive, you can use the name without having to fully qualify it every time.

  3. Add the following code to the _tmain function, to create a SortedList and add some data to it:

    SortedList* psl = new SortedList(); psl->Add(new String("Dilbert"), __box(1044)); psl->Add(new String("Wally"), __box(2213)); psl->Add(new String("Ted"), __box(1110)); psl->Add(new String("Alice"), __box(3375));

    As with the ArrayList discussed in the previous section, a SortedList has a default capacity and will automatically increase its capacity as necessary. Alternative constructors let you create SortedList classes with particular initial capacities, and you can trim excess using the TrimToSize function.

    You can also use the set_Item method to add a key/value pair. This has the same syntax as Add, and in C++, there is no difference between using set_Item and Add.

    Note

    Keys can’t be null pointers, but you can use null pointers as values.

  4. Add some code to print out the contents of the SortedList.

    for (int i=0; i<psl->get_Count(); i++) Console::WriteLine(psl->GetByIndex(i));

    The loop uses the GetByIndex function to retrieve each value in turn, and you’ll find when you run the code that the values are printed in the order 3375-1044-1110-2213, which reflects the alphabetical order of the keys.

  5. In addition to retrieving values by index, you can retrieve them by key, like this:

    Console::WriteLine(S"Value for key ’Alice’ is {0}", psl->get_Item(new String("Alice")));

    The get_Item method checks its argument and returns the associated value if a match is found. If no match is found, a null pointer is returned.

  6. You can also modify entries in the list by key or by value, like this:

    // Change the value associated with key ’Alice’ psl->set_Item(new String("Alice"), __box(5555)); // Change the value at index 3 psl->SetByIndex(3, __box(1010));

    The set_Item method stores a value against a key. If the key already exists, its associated value is overwritten; if it doesn’t exist, a new key/value pair is created. SetByIndex will work only on existing keys and replaces the value at a given index.

Other SortedList Operations

You can use the IndexOfKey and IndexOfValue methods to return the index of a given key or value, and both of them will return -1 if the key or value you specify doesn’t exist in the collection. Likewise, the ContainsKey and ContainsValue functions will return true if the collection contains a given value or key.

If you want to delete items from the collection, Remove can be used to remove an item by key. RemoveByIndex does the same thing by index, and Clear can be used to remove all entries.

The StringCollection Class

The StringCollection class, defined in the System::Collections::Specialized namespace, represents a collection of strings. StringCollection lets you access elements by index, and it lets you add, remove, and insert items.

Because the StringCollection class implements the ICollection, IEnumerable, and IList interfaces, the class implements the methods associated with those interfaces, so it provides a lot of functionality that you’ve already met, such as Clear, Count, Contains, and CopyTo.

In the following brief exercise, you’ll create a StringCollection and see how to use it.

  1. Open Visual Studio, and create a new Visual C++ Console Application (.NET) project named StringCollection.

  2. Open the StringCollection.cpp source file, and add the following line immediately after the using namespace System; line:

    using namespace System::Collections::Specialized;

    The StringCollection class is defined in the System::Collections::Specialized namespace.

  3. Add the following code to the _tmain function to create a StringCollection and add some data to it:

    StringCollection* psc = new StringCollection(); psc->Add(new String("Rhyl")); psc->Add(new String("Prestatyn")); psc->Add(new String("Abersoch")); psc->Add(new String("Nefyn"));

    Unlike ArrayList and SortedList, StringCollection objects are created with no initial capacity and simply grow as more items are added.

  4. Because StringCollection implements the ICollection, IList, and IEnumerable interfaces, it supports much of the same functionality as the other classes we’ve discussed, including the ability to use enumerators. Add some code to the end of _tmain to print the contents of the collection:

    StringEnumerator* ie = psc->GetEnumerator(); while (ie->MoveNext()) Console::WriteLine(S"string is {0}", ie->Current);




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net