< C++ .NET Arrays & Collections 9 | Main | C++ .NET Arrays & Collections 11 >


 

 

More On Arrays and Collections 10

 

 

What we have in this page?

 

  1. Other ArrayList Operations (continue)

  2. The SortedList Class

 

 

The following code example shows how to set and get a range of elements in the ArrayList.

// SortedList.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

using namespace System::Collections;

void PrintValues(IEnumerable^ myList, char mySeparator);

 

int main(array<System::String ^> ^args)

{

      // Creates and initializes a new ArrayList.

      ArrayList^ myAL = gcnew ArrayList;

      myAL->Add("The");

      myAL->Add("quick");

      myAL->Add("brown");

      myAL->Add("fox");

      myAL->Add("jumped");

      myAL->Add("over");

      myAL->Add("the");

      myAL->Add("lazy");

      myAL->Add("dog");

      // Creates and initializes the source ICollection.

      Queue^ mySourceList = gcnew Queue;

      mySourceList->Enqueue("big");

      mySourceList->Enqueue("gray");

      mySourceList->Enqueue("wolf");

      // Displays the values of five elements starting at index 0.

      ArrayList^ mySubAL = myAL->GetRange(0, 5);

      Console::WriteLine("Index 0 through 4 contains:");

      PrintValues(mySubAL, ' ');

      Console::WriteLine();

      // Replaces the values of five elements starting at

      // index 1 with the values in the ICollection.

      myAL->SetRange(1, mySourceList);

      // Displays the values of five elements starting at index 0.

      mySubAL = myAL->GetRange(0, 5);

      Console::WriteLine("Index 0 through 4 now contains:");

      PrintValues(mySubAL, ' ');

      Console::WriteLine(); 

      return 0;

}

 

void PrintValues(IEnumerable^ myList, char mySeparator)

{

   IEnumerator^ myEnum = myList->GetEnumerator();

   while (myEnum->MoveNext())

   {

      Object^ obj = safe_cast<Object^>(myEnum->Current);

      Console::Write("{0} {1}", mySeparator, obj);

   }

   Console::WriteLine();

}

 

Output:

 

A code example shows how to set and get a range of elements in the ArrayList

 

 

 

 

The SortedList Class

 

The SortedList class, also defined in the System::Collections namespace, represents a collection of keys and values pairs that are sorted by the keys and are accessible by key and by index. The syntax is:

[SerializableAttribute]

[ComVisibleAttribute(true)]

public ref class SortedList : IDictionary, ICollection, IEnumerable, ICloneable

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. 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:

  1. 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.

  2. 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.

 

1.        Open Visual C++/Studio, and create a new CLR Console Application project named SortedList.

 

Creating a new C++ .NET CLR Console Application project named SortedList

 

 

 

 

2.        Open the SortedList.cpp source file and try the following example on how to create and initialize a SortedList and how to print out its keys and values.

// SortedList.cpp : main project file.

#include "stdafx.h"

 

#using <system.dll>

 

using namespace System;

using namespace System::Collections;

public ref class SamplesSortedList

{

   public:

     static void PrintKeysAndValues(SortedList^ myList)

     {

        Console::WriteLine("\t-KEY-\t-VALUE-");

        for (int i = 0; i < myList->Count; i++)

        {

          Console::WriteLine("\t{0}:\t{1}", myList->GetKey(i), myList->GetByIndex(i));

        }

        Console::WriteLine();

     }

};

 

int main(array<System::String ^> ^args)

{

   // Creates and initializes a new SortedList.

   Console::WriteLine("New SortedList created and initialized...");

   SortedList^ mySL = gcnew SortedList;

   // The key and value pairs...

   mySL->Add("First", "Hello");

   mySL->Add("Second", "Cruel");

   mySL->Add("Third", "World");

   Console::WriteLine();

   // Displays the properties and values of the SortedList.

   Console::WriteLine("The properties and values of the mySL SortedList...");

   Console::WriteLine("  Count:    {0}", mySL->Count);

   Console::WriteLine("  Capacity: {0}", mySL->Capacity);

   Console::WriteLine("  Keys and Values:");

   SamplesSortedList::PrintKeysAndValues(mySL);

   return 0;

}

 

Output:

 

 

 

 

An example on how to create and initialize a SortedList and how to print out its keys and values program

 

A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation. A SortedList internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be. The capacity of a SortedList is the number of elements the SortedList can hold. The default initial capacity for a SortedList is 0. As elements are added to a SortedList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. The elements of a SortedList are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.

The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList. Operations on a SortedList tend to be slower than operations on a Hashtable because of the sorting. However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the SortedList is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection. Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. A SortedList can support multiple readers concurrently, as long as the collection is not modified. To guarantee the thread safety of the SortedList, all operations must be done through the wrapper returned by the Synchronized method. Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

 

 

Part 1 | Part 2 | part 3 | Part 4 | Part 5 | Part 6

 

 


 

< C++ .NET Arrays & Collections 9 | Main | C++ .NET Arrays & Collections 11 >