Last Updated:

Example of the ArrayList class - C++

String *pStr = String::Format(// Format
"id {0} {!}", _box(id), S"not found");
// "identifier {0} {!}", (identifier),
// " not found");
throw new Exception(pStr); // new Exception
}
void ShowCustomers(int id) // identifier
{
if ('Checkld(id) && id '= -1)
// if (! checkld(id) && id!=-1)
return; lEnumerator *pEnum =
pCustomers-XSetEnumerator();
while (pEnum › MoveNext())
{
Customer *pCust = // Customer
dynamic_cast<Customer *>(pEnum › Current); // Client
if (id == - 1 || id == pCust › nCustomer!d)
// if (id == -1 ||
// identifier == pCust › nCustomerld)
{
String *pSid =
pCust › nCustomerId.ToStnng() › PadLeft(4);
String *pFirst =
pCust › pFirstName › PadRight(12);
String *pLast =
pCust › pLastName › PadRight(12);
String *pEmail =
pCust › pEmailAddress › PadRight(20);
Console::Write("{0} ", pSid); // Console:: Write
Console::Write("{0} ", pFirst); // Console:: Write
Console::Write("{0} ", pLast); // Console:: Write
Console::WriteLine("{0}", pEmail); // Console:: Write
}
}
}
bool CheckId(int id)
// logical {boolean} Checkld (int identifier)
{
Customer *pCust = new Customer(id);
// Client *pCust = new Client (id);
return pCustomers › Contains(pCust); // Contains?
}
};

To navigate through the collection, use the lEnumerator interface. It can be used in this case because the ArrayList supports the lEnumerable interface. This interface provides support for the special semantics of C# – the semantics of foreach. The foreach keyword is not supported in C++. However, the following example shows that in managed C++, you can use the lEnumerable interface to iterate through arraylist elements. Interfaces for working with collections, including lenumerable, will be discussed later in this chapter.

The Add and Remove methods, as their names suggest, are used to add and remove items in the collection, respectively. The Remove method scans the collection for an item equal to the item passed to the method as an argument, and deletes the found item. The equality of the elements is established by calling the Equals method.

The Remove method is passed as an argument to the element created by the special constructor we implemented, and the identifier is used to create the element. Because we've spoofed the Equals method so that the equality of elements is set only by the CustomerlD attribute, this constructor has a single argument, the client ID.

The Contains method, which we use in the Checkld helper method, uses the spoofed Equals method in the same way.

By using collections, you can easily add and remove items. When you use arrays for the same purpose, you need to write a lot of code instead of collections to insert and move the elements of the array, and to fill in the empty space left after the element is deleted. In addition, collections do not have a specific size, and can be dynamically enlarged if necessary.