XPCOM array guide

  • Revision slug: XPCOM_array_guide
  • Revision title: XPCOM array guide
  • Revision id: 66899
  • Created:
  • Creator: Nickolay
  • Is current revision? No
  • Comment /* Usage */

Revision Content

Introduction

Array types

Mozilla has many array classes because each array is optimized for a particular usage pattern. This guide describes the available arrays as well as the enumerator classes that can be used to get to them. In this document the term Array refers to a container for multiple objects with a numeric, zero-based index.

The standard array classes are:

  • nsIArray - a scriptable container for scriptable XPCOM objects. This array is read-only, and the interface does not provide any methods that will allow adding and removing members.
  • nsIMutableArray - a scriptable container for scriptable XPCOM objects, which allows addition and removal of member objects. This interface actually derives from nsIArray.
  • nsCOMArray<T> - a C++ class which provides a typesafe, reference-counted container for pointers to a single type of COM object. This class is more or less a wrapper around nsVoidArray and thus shares most of its semantics.
  • nsTArray<T> - a C++ class which provides a typesafe container for objects or primitive types (pointers, integers, etc). The objects must define a default constructor and a copy constructor. To use IndexOf without providing a comparator, they must also define an operator==. For sorting without providing a comparator they must define an operator<. Note that this class differs from the other array types by using unsigned indices.
  • nsVoidArray - a C++ class which provides a generic container for any objects using the generic void * type.
  • nsStringArray / nsCStringArray - a set of C++ classes for holding lists of string objects. Derived from nsVoidArray
  • nsAutoVoidArray - a version of nsVoidArray which includes 8 entries of internal storage for the array data.
  • nsSmallVoidArray - a replacement for nsVoidArray which is optimized to hold zero or one element.

This handy chart may make it easier to understand the different arrays:

ClassData TypeScriptable?Typesafe?Can be modified?Built in buffer?Ownership
nsIArray XPCOM object Yes No No No Reference Counted, Weak/Strong
nsIMutableArray XPCOM object Yes No Yes No Reference Counted, Weak/Strong
nsCOMArray<T> XPCOM object No Yes Yes* No Reference Counted, Strong
nsTArray<T> Any that has a default constructor and copy constructor No Yes Yes* No Can hold objects directly, in which case it owns them. When holding pointers, doesn't own the pointer.
nsVoidArray Any No No Yes* No Weak / None
nsStringArray
nsCStringArray
nsString
nsCString
No Yes Yes* No Private (copies strings)
nsAutoVoidArray Any No No Yes* Yes Weak / None
nsSmallVoidArray Any No No Yes* No Weak / None
nsISupportsArray XPCOM Object Yes No Yes* No Reference Counted, Strong

(*) Note: Concrete C++ arrays can be made read-only by declaring them const. For example:

// HandleList cannot modify the array because of const
void HandleList(const nsVoidArray&);

In-place enumeration

Most of the arrays presented here provide callback-style means to enumerate members of an array. Instead of incrementally accessing each element of the array by its index, the arrays provide a way to pass in a callback function that will be called for each element in the array.

For most concrete C++ classes like nsVoidArray and nsCOMArray<T>, indexing should be faster than the callback-style enumeration, because accessing an indexed member of such an array is usually very fast, while enumeration has slight function call overhead. In the case of scriptable arrays like nsIArray however, the enumeration mechanism is often preferred because it avoids the AddRef / Release overhead that comes from accessing each object.

The only functional drawback to in-place enumeration is that you cannot manipulate the array itself during the enumeration. For example, you should not delete elements of an array during the enumeration as this will often confuse the loop which is enumerating the array.

Enumerators

Most arrays provide access to an object which is used to enumerate members of the array. These Enumerators maintain state about the current position in the array. Enumerators are used to access the elements in an ordered way, without relying on the underlying array type. These enumerators include:

  • nsISimpleEnumerator - an enumerator for COM objects.
  • nsIStringEnumerator / nsIUTF8StringEnumerator - enumerators for strings

Obsolete arrays / enumerators

There are some deprecated classes which should not be used by new code.

  • nsISupportsArray - obsoleted by nsIArray, use that instead.
  • nsIEnumerator - obsoleted by nsISimpleEnumerator, use that instead.
  • nsIBidirectionalEnumerator - obsoleted by nsISimpleEnumerator, use that instead.
  • nsVoidArray - nsTArray<T> is preferred. Using nsAutoVoidArray is still ok, since that saves an allocation over using nsTArray<T>(8).

Which Array should I use?

Do not use nsISupportsArray; it is deprecated.

Does your array need to be scriptable? If so, use nsIArray.

Example: an array attribute in an IDL file would be nsIArray.

Will your array store non-refcounted objects and need automatic resizing? If so, use nsTArray<T>.

Example: an array of integers or an array of strings.

Will your array store non-refcounted objects and be a fixed size? If so, just use a native C++ array unless you need the enumeration options on nsTArray<T>.

Example: an array of error message static const char* pointers.

Are all the things you are storing interface pointers to instances of the same interface? If so, use nsCOMArray.

Example: a content node's list of nsIContent children.

Otherwise use nsIArray and make liberal use of QueryElementAt().

The point of nsCOMArray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be able to use it because you get type-safety and don't have to spend time and code QIing (like you have to with nsIArray).

Array Guidelines

Here are a few simple rules which will keep your code clean and your developers happy:

  • Use typesafe arrays like nsCOMArray<T> nsTArray<T> wherever possible.
  • Avoid all obsolete arrays and enumerators.
  • Avoid creating temporary arrays.

Scriptable Arrays

nsIArray / nsIMutableArray

Usage

nsIArray is useful if you need to pass arrays of COM objects through interfaces or require a scriptable array. It can hold strong or weak references to its container objects. This basic interface only allows querying of existing elements in the array. The methods that modify the array have been broken out into nsIMutableArray.

An nsIArray implementation can be created from C++ or JavaScript using createInstance and the contract ID "@mozilla.org/array;1". The created array implements nsIMutableArray and nsIArray. Since nsIMutableArray derives from nsIArray, the resulting array can be cast to a read-only array.

C++ Example

void GetList(nsIArray** aResult) {
  nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID);

  // append some elements
  ...

  // return it to the caller
  *aResult = array;
  NS_ADDREF(*aResult);
}

JavaScript Example

function getList() {
  var array = Components.classes["@mozilla.org/array;1"]
                        .createInstance(Components.interfaces.nsIMutableArray);
  // append some elements
  ...

  // return it to the caller
  return array;
}

Access to elements

Since nsIArray is a regular XPCOM object, its interfaces follows the standard conventions of ownership. Access to specific elements is through QueryElementAt, which is similar to QueryInterface, but it takes a specific index.

void NotifyObservers(nsIArray* aArray) {
  PRUint32 length;
  aArray->GetLength(&length);
  for (PRUint32 i=0; i<length; ++i) {
    nsCOMPtr<nsIMyObserver> element;
    aArray->QueryElementAt(i, NS_GET_IID(nsIElement),
                                getter_AddRefs(element));
    element->Observe();
  }
}

A simpler option is to use the helper do_QueryElementAt which is typesafe.

void NotifyObservers(nsIArray* aArray) {
  PRUint32 length;
  aArray->GetLength(&length);
  for (PRUint32 i=0; i<length; ++i) {
    nsCOMPtr<nsIMyObserver> element =
    do_QueryElementAt(aArray, i);
     element->Observe();
  }
}

Passing as a parameter

Since nsIArray is an XPCOM object, it should be passed as a pointer. To distinguish between read-only arrays and writable arrays, you should make sure to pass a nsIArray or nsIMutableArray as appropriate.

When the array can or should be modified, then use nsIMutableArray:

// array is read-only because it uses nsIArray
void PrintSize(nsIArray* elements) {
  PRUint32 count;
  elements->GetLength(&count);
  printf("There are %d elements.\n", count);
}

// using nsIMutableArray, so callee may modify
void TweakArray(nsIMutableArray* elements) {
  elements->RemoveElementAt(0);
  elements->AppendElement(newElement, PR_FALSE);
}

While it is usually possible to call QueryInterface on an nsIArray to get access to the nsIMutableArray interface, this is against convention and it should be avoided.

// no need for the double-pointer, and this violates XPCOM rules
// which expect acess to a new object
void TweakArray(nsIMutableArray** elements) {
  // ugh, extra indirection!
  *elements->RemoveElementAt(0);
  *elements->AppendElement(newElement, PR_FALSE);
}

In-place enumeration

When accessing all members of an nsIArray, in-place enumeration is preferred over indexed access. However, I seem to have forgotten to implement that. Good thing the interface is under review. Sorry!

Enumerators

Creating an enumerator from an nsIArray is easy. The method Enumerate() returns a nsISimpleEnumerator which accesses all the elements in the array. Often, simply accessing an array by index, using QueryElementAt is faster. See the section on Enumerators to learn when to properly use enumerators.

For example, if you need to iterate an array returned from another object, you might use Enumerate().

...
// get the array
nsCOMPtr<nsIArray> array;
foo->GetElements(getter_AddRefs(array));

// make an enumerator
nsCOMPtr<nsISimpleEnumerator> enumerator;
array->Enumerate(getter_AddRefs(enumerator));

// now enumerate the elements
...

Typesafe Arrays

nsCOMArray<T>

nsCOMArray<T> is a typesafe wrapper around nsVoidArray, so it has a similar API. It enforces both typesafety and XPCOM reference counting by keeping an owning reference to each element in the array.

Usage

It is most often used as a member of a C++ class to store a list of well-typed XPCOM objects. It is also usually declared as an inline member rather than a pointer. As a class member, nsCOMArray<T> is preferred over nsIArray when access to the array is confined to the class itself.

For example, here is its use in a class:

class NodeContainer {
public:
  void AddNode(nsINode* node);
   
private:
  nsCOMArray<nsINode> mNodes;
};

// typesafety of mNodes ensures that we only append an nsINode*
void NodeContainer::AddNode(nsINode* node) {
  mNodes.AppendObject(node);
}
   

nsCOMArray<T> can also be declared on the stack to collect a temporary list of objects and manipulate them. When the object goes out of scope, all its members are released.

void ProcessVisibleItems()
{
  // temporary stack-based nsCOMArray
  nsCOMArray<nsIFoo> fooItems;
  GetCompleteList(fooItems);
   
  // now filter out non visible objects
  // doing this backwards
  PRUint32 i = fooItems.Count();
  while (i > 0) {
    --i;
    PRBool isVisible;
    fooItems[i]->GetIsVisible(&isVisible);
    if (!isVisible) {
      fooItems.RemoveObjectAt(i);
    }
  }

  // now deal with the processed list
  ProcessList(fooItems);

  // fooItems will release all its members
  // when it goes out of scope
}

Access to elements

nsCOMArray<T> is a concrete C++ class, and so the [] operator is used to access its members. When using the [] operator, the reference count is unchanged. This allows direct processing of array elements without worrying about calling Release().

For example, this code calls the same method on each member:

void NotifyObservers(const nsCOMArray<nsIMyObserver>& observers) {
  // Using [] doesn't leak!
  for (PRInt32 i = observers.Count() - 1; i >= 0 ; i--)
    observers[i]->Observe();
}

Be careful with this though, you could end up with a weak pointer if you're converting from non-nsCOMArray code.

// old version, relied on automatic addref
// mElements is an nsISupportsArray*
void GetFirstObject(nsIElement** aResult) {
  // no need to call NS_ADDREF - this does it for you
  mElements->QueryElementAt(0, NS_GET_IID(nsIElement),
  (void**)aResult);
}
  
// new version, make sure to call NS_ADDREF()
// mElements is now a nsCOMArray<nsIElement>
void GetFirstObject(nsIElement** aResult) {
  *aResult = mElements[0];
  NS_ADDREF(*aResult);
}

Passing as a parameter

When passing nsCOMArray<T> among functions, the convention is to pass by reference. Also be sure to use const if you want to enforce that the array is read-only.

Here is an example with a read-only and a writable array:

// array is read-only because of const
void PrintSize(const nsCOMArray<nsIElements>& elements) {
 printf("There are %d elements.\n", elements.Count());
}

// no const, so we can modify the array
void TweakArray(nsCOMArray<nsIElement>& elements, nsIElement* newElement) {
  elements.RemoveObjectAt(0);
  elements.AppendObject(newElement);
}

In-place enumeration

The callback-based enumeration in nsCOMArray<T> is about as fast as, if not faster than, standard loop-based iteration. The callback mechanism can be useful when integrating with existing callback-style code however.

One particularly nice thing about the callback mechanism is that it is typesafe. For instance:

PR_CALLBACK PRBool getFirstVisible(nsIElement* element, void* closure)   {
 PRBool isVisible;
 element->IsVisible(&isVisible);

 // stop at first object
 if (isVisible) {
  NS_STATIC_CAST(ClosureObject*,closure)->element = element;
  return PR_FALSE;
 }
 return PR_TRUE;
}

...
// enumerate to find the object
ClosureObject closureObject = { 0 };
if (!mElements.EnumerateForwards(getFirstVisible, closureObject))
             processElement(closureObject->element);
...

Enumerators

A nsISimpleEnumerator can be created to provide access to a nsCOMArray<T>. When the enumerator is created, it takes a snapshot of the elements in the array, so that the enumerator can outlive the array.

To create the enumerator, use NS_NewArrayEnumerator(nsISimpleEnumerator**, const nsCOMArray<T>&). For example:

// mElements is an nsCOMArray<nsIElement>
nsFoo::GetElements(nsISimpleEnumerator** aResult) {
  return NS_NewArrayEnumerator(aResult, mElements);
}

nsTArray<T>

nsTArray<T> is a typesafe array for holding various objects. It can be used to hold objects directly, not just pointers to objects.

Usage

It is most often used as a member of a C++ class to store a list of well-typed objects. It is also usually declared as an inline member rather than a pointer. As a class member, nsTArray<T> is preferred over nsVoidArray.

For example, here is its use in a class:

class MediaList {
public:
  void AddMedium(const nsString& aMedium);
   
private:
  nsTArray<nsString> mMedia;
};

// typesafety of mMedia ensures that we only append an nsString
void NodeContainer::AddMedium(const nsString& aMedium) {
  mMedia.AppendElement(aMedium);
}
   

nsTArray<T> can also be declared on the stack to collect a temporary list of objects and manipulate them. When the object goes out of scope, all its members have their destructors called. Note that if the nsTArray<T> holds pointers to objects, the objects will not be deleted (and hence not have their destructors called).

void ProcessVisibleItems()
{
  // temporary stack-based nsTArray
  nsTArray<FooStruct> fooItems;
  GetCompleteList(fooItems);
   
  // now filter out non visible objects
  // doing this backwards
  PRUint32 i = fooItems.Length();
  while (i > 0) {
    --i;
    PRBool isVisible;
    fooItems[i]->GetIsVisible(&isVisible);
    if (!isVisible) {
      fooItems.RemoveElementAt(i);
    }
  }

  // now deal with the processed list
  ProcessList(fooItems);

  // fooItems will call the destructors of all the FooStruct objects
  // when it goes out of scope
}

Access to elements

nsTArray<T> is a concrete C++ class, and so the [] operator is used to access its members.

For example, this code calls the same method on each member:

void NotifyObservers(const nsTArray<ObserverClass*>& observers) {
  for (PRUint32 i = observers.Length(); i > 0 ; ) {
    --i;
    observers[i]->Observe();
  }
}

Passing as a parameter

When passing nsTArray<T> among functions, the convention is to pass by reference. Also be sure to use const if you want to enforce that the array is read-only.

Here is an example with a read-only and a writable array:

// array is read-only because of const
void PrintSize(const nsTArray<nsElement>& elements) {
 printf("There are %d elements.\n", elements.Length());
}

// no const, so we can modify the array
void TweakArray(nsTArray<nsElement>& elements, 
                const nsElement& newElement) {
  elements.RemoveElementAt(0);
  elements.AppendElement(newElement);
}

In-place enumeration

There are no enumerator objects that work on an nsTArray<T>.

C++ Arrays

nsVoidArray

nsVoidArray is a concrete C++ class that allows for storage of any arbitrary object. The base type for all objects is void *. When converting to/from a void *, use NS_STATIC_CAST to ensure that no const-ness is lost.

Note that nsVoidArray defines no semantics of ownership of its objects. Depending on its use, the array may either own the objects that it points to, or its member may be pointers to existing objects that are owned by another data structure. Because nsVoidArray itself does not define any ownership rules, it is up to the consumer to know when it is appropriate to free objects out of the array.

This implies that when an nsVoidArray goes out of scope, seperate code must free any memory that is semantically owned by the array. This should always be documented in the declaration of the array instance.

nsCOMArray<T> was designed to eliminate some of the overhead of using nsVoidArray when using COM objects. If your code is using nsVoidArray to keep references to COM objects, consider converting it to nsCOMArray<T>.

Usage

nsVoidArray is often used as a member variable in a class. Remember to document ownership!

struct FooElement {
 ...
};

class nsFoo : nsIFoo {
 ...
 virtual ~nsFoo();
 ...
 
 private:
 // mElements owns a list of FooElement structs,
 // which must be deleted when this object goes away
 nsVoidArray mElements;

 // mVisibleElements contains weak (non-owning) references
 // to elements in mElements, and does not need to be cleaned up
 nsVoidArray mVisibleElements;
};

nsFoo::~nsFoo() {
 // mVisibleElements is fine, but
 // don't forget to clean up mElements!
 PRUint32 i, count = mElements.Count();
 for (i=0; i<count; ++i)
  delete NS_STATIC_CAST(FooElement*, mElements[i]);
 }
   

As you can see, nsVoidArray has some context-specific overhead to make sure memory is cleaned up appropriately.

Access to elements

The [] operator is used to access member variables. Don't forget to use NS_STATIC_CAST().

for (i=0; i<count; ++i) {
 FooElement* element = NS_STATIC_CAST(FooElement*,mElements[i]);
 // now manipulate element
}
   

Passing as a parameter

Like other concrete C++ classes, passing by reference using the & syntax is preferred.

In-place enumeration

Enumerators

nsStringArray / nsCStringArray

Usage

Access to elements

Passing as a parameter

In-place enumeration

Enumerators

nsAutoVoidArray

Usage

Access to elements

Passing as a parameter

In-place enumeration

Enumerators

nsSmallVoidArray

Usage

Access to elements

Passing as a parameter

In-place enumeration

Enumerators

Enumerators

Enumerators are very simple, structure-free objects for visiting each member of a set of objects. The enumerators are used as a generic interface for arrays, hashtables, and other constructs which contain one or more objects. When designing public interfaces, enumerators are the preferred mechanism for accessing these structures because they hide the details of the implementation behind the interface.

nsISimpleEnumerator

nsISimpleEnumerator is a generic enumerator for enumerating a list of any XPCOM object. There are many implementations of nsISimpleEnumerator, including one that enumerates nsIArray objects, and another one for nsCOMArray. It is very common for other interfaces which support nsISimpleEnumerator to make their own implementations.

nsIStringEnumerator

String enumerators provide an easy way to pass a list of strings around with minimal copying. Both unicode strings and UTF8-encoded strings are supported. For more information about the different types of strings, see the String Guide.

String enumerators can be created from nsStringArray or nsCStringArray objects. The implementation of the string enumerator interfaces for nsStringArray and nsCStringArray supports conversion between UTF8 and Unicode, and can be QueryInterface'd back and forth between nsIStringEnumerator and nsIUTF8StringEnumerator.

To create an nsIStringEnumerator for an nsStringArray, you can use one of the variations of NS_NewStringEnumerator. There are also corresponding enumerators and helpers for UTF8 strings. In the examples below, NS_NewUTF8StringEnumerator can be used along with nsIUTF8StringEnumerator and nsCStringArray.

This first example demonstrates the case where a class which owns an nsStringArray, and are returns an nsIStringEnumerator to a caller. You can use the variation of NS_NewStringEnumerator that ensures the owner of the array outlives the enumerator. This is necessary because nsStringArray is not reference counted. Without holding a reference to the owner, the enumerator could be left with a dangling pointer to a deleted nsStringArray.

class nsFoo : nsIFoo {
...
private:
  nsStringArray mElementNames;
};

nsFoo::GetElementNames(nsIStringEnumerator** aResult)
{
  // pass in "this" to make sure the enumerator
  // holds a reference to "this"
  return NS_NewStringEnumerator(aResult, mElementNames, this);
}

One variant of NS_NewStringEnumerator does not require an owner, but should only be used when the lifetime of the enumerator is known to be shorter than that of the array. Often this is used when a method must take a nsIStringEnumerator rather than an nsStringArray, due to some sort of interface constraint.

class nsFoo : nsIFoo {
 ...
 // when ProcessElements returns, the enumerator is at the
 // end of the list, and can be released.
 NS_IMETHODIMP ProcessNames(nsIStringEnumerator*);
 private:
   
 nsStringArray mElementNames;
};

...
nsCOMPtr<nsIStringEnumerator> enumerator;
NS_NewStringEnumerator(getter_AddRefs(enumerator), mElementNames);

// now call a method on "this" that has a known behavior
ProcessNames(enumerator);
// now enumerator is used up, and can be released
...

The last version of nsIStringEnumerator takes ownership of an nsStringArray and is responsible for freeing the array when the enumerator is used up.

void GetNames(nsIStringEnumerator** aResult)
{
 nsStringArray *resultArray = new nsStringArray;
 resultArray->AppendString(str1);
 resultArray->AppendString(str2);
 
 // enumerator will free resultArray
 return NS_NewAdoptingStringEnumerator(aResult, resultArray);
}

As noted above, these implementations of nsIStringEnumerator can also be QueryInterface'd between nsIStringEnumerator and nsIUTF8StringEnumerator. The implementations will properly convert back and forth between UTF8 and Unicode. To ensure that you get the right implementation and the conversion is done in the right direction, make sure that you call the version of NS_NewStringEnumerator or NS_NewUTF8StringEnumerator that corresponds to the array type, not the enumerator type.

For example, if a class has an internal nsCStringArray of UTF8 strings, but needs to implement an interface which returns an nsIStringEnumerator, it should use NS_NewStringEnumerator:

class nsFoo : nsIFoo {
 ...
 NS_IMETHOD GetStrings(nsIStringEnumerator** aResult);
 private:
 nsCStringArray mElementNames;
};

NS_IMETHODIMP
nsFoo::GetStrings(nsIStringEnumerator** aResult) {
 nsresult rv;
 nsCOMPtr<nsIUTF8StringEnumerator> enumerator
 rv = NS_NewUTF8StringEnumerator(getter_AddRefs(enumerator),
                                       mElementNames, this);
 return CallQueryInterface(enumerator, aResult);
}

Obsolete Arrays and Enumerators

nsISupportsArray

nsIEnumerator (includes nsIBidirectionalEnumerator)

Revision Source

<p>
</p>
<h2 name="Introduction"> Introduction </h2>
<h4 name="Array_types">Array types</h4>
<p>Mozilla has many array classes because each array is optimized for a particular usage pattern. This guide describes the available arrays as well as the enumerator classes that can be used to get to them. In this document the term Array refers to a container for multiple objects with a numeric, zero-based index.
</p><p>The standard array classes are:
</p>
<ul><li> <code><a href="#nsIArray_.2F_nsIMutableArray">nsIArray</a></code> - a scriptable container for scriptable XPCOM objects. This array is read-only, and the interface does not provide any methods that will allow adding and removing members.
</li><li> <code>nsIMutableArray</code> - a scriptable container for scriptable XPCOM objects, which allows addition and removal of member objects. This interface actually derives from nsIArray.
</li><li> <code>nsCOMArray<span class="nowiki">&lt;T&gt;</span></code> - a C++ class which provides a typesafe, reference-counted container for pointers to a single type of COM object. This class is more or less a wrapper around nsVoidArray and thus shares most of its semantics.
</li><li> <code>nsTArray<span class="nowiki">&lt;T&gt;</span></code> - a C++ class which provides a typesafe container for objects or primitive types (pointers, integers, etc). The objects must define a default constructor and a copy constructor. To use <code>IndexOf</code> without providing a comparator, they must also define an <code>operator==</code>. For sorting without providing a comparator they must define an <code><span class="nowiki">operator&lt;</span></code>. Note that this class differs from the other array types by using unsigned indices.
</li><li> <code>nsVoidArray</code> - a C++ class which provides a generic container for any objects using the generic void * type.
</li><li> <code>nsStringArray</code> / <code>nsCStringArray</code> - a set of C++ classes for holding lists of string objects. Derived from nsVoidArray
</li><li> <code>nsAutoVoidArray</code> - a version of nsVoidArray which includes 8 entries of internal storage for the array data.
</li><li> <code>nsSmallVoidArray</code> - a replacement for nsVoidArray which is optimized to hold zero or one element. </li></ul>
<p>This handy chart may make it easier to understand the different arrays:
</p>
<table class="fullwidth-table"> <tbody><tr><th>Class</th><th>Data Type</th><th>Scriptable?</th><th>Typesafe?</th><th>Can be modified?</th><th>Built in buffer?</th><th>Ownership</th></tr> <tr class="even"><td><code><a href="#nsIArray_.2F_nsIMutableArray">nsIArray</a></code></td> <td>XPCOM object</td> <td>Yes </td><td>No</td> <td>No</td> <td>No</td> <td>Reference Counted, Weak/Strong</td> </tr> <tr class="odd"><td><code>nsIMutableArray</code></td> <td>XPCOM object</td> <td>Yes </td><td>No</td> <td>Yes</td> <td>No</td> <td>Reference Counted, Weak/Strong</td> </tr> <tr class="even"><td><code>nsCOMArray&lt;T&gt;</code></td> <td>XPCOM object</td> <td>No </td><td>Yes</td> <td>Yes*</td> <td>No</td> <td>Reference Counted, Strong</td> </tr> <tr class="odd"><td><code>nsTArray&lt;T&gt;</code></td> <td>Any that has a default constructor and copy constructor</td> <td>No</td> <td>Yes</td> <td>Yes*</td> <td>No</td> <td>Can hold objects directly, in which case it owns them. When holding pointers, doesn't own the pointer.</td> </tr> <tr class="even"><td><code>nsVoidArray</code></td> <td>Any</td> <td>No </td><td>No</td> <td>Yes*</td> <td>No</td> <td>Weak / None</td> </tr> <tr class="odd"><td><code>nsStringArray</code><br><code>nsCStringArray</code></td> <td><code>nsString</code><br><code>nsCString</code></td> <td>No </td><td>Yes</td> <td>Yes*</td> <td>No</td> <td>Private (copies strings)</td> </tr> <tr class="even"><td><code>nsAutoVoidArray</code></td> <td>Any</td> <td>No </td><td>No</td> <td>Yes*</td> <td>Yes</td> <td>Weak / None</td> </tr> <tr class="odd"><td><code>nsSmallVoidArray</code></td> <td>Any</td> <td>No </td><td>No</td> <td>Yes*</td> <td>No</td> <td>Weak / None</td> </tr> <tr class="even"><td><code>nsISupportsArray</code></td> <td>XPCOM Object</td> <td>Yes </td><td>No</td> <td>Yes*</td> <td>No</td> <td>Reference Counted, Strong</td> </tr>
</tbody></table>
<p>(*) Note: Concrete C++ arrays can be made read-only by declaring them const. For example:
</p>
<pre class="eval">// HandleList cannot modify the array because of const
void HandleList(const nsVoidArray&amp;);
</pre>
<h4 name="In-place_enumeration"> In-place enumeration </h4>
<p>Most of the arrays presented here provide callback-style means to enumerate members of an array. Instead of incrementally accessing each element of the array by its index, the arrays provide a way to pass in a callback function that will be called for each element in the array.
</p><p>For most concrete C++ classes like <code>nsVoidArray</code> and <code>nsCOMArray&lt;T&gt;</code>, indexing should be faster than the callback-style enumeration, because accessing an indexed member of such an array is usually very fast, while enumeration has slight function call overhead. In the case of scriptable arrays like nsIArray however, the enumeration mechanism is often preferred because it avoids the AddRef / Release overhead that comes from accessing each object.
</p><p>The only functional drawback to in-place enumeration is that you cannot manipulate the array itself during the enumeration. For example, you should not delete elements of an array during the enumeration as this will often confuse the loop which is enumerating the array.
</p>
<h4 name="Enumerators"> Enumerators </h4>
<p>Most arrays provide access to an object which is used to enumerate members of the array. These Enumerators maintain state about the current position in the array. Enumerators are used to access the elements in an ordered way, without relying on the underlying array type.
These enumerators include:
</p>
<ul><li> <code>nsISimpleEnumerator</code> - an enumerator for COM objects.
</li><li> <code>nsIStringEnumerator</code> / <code>nsIUTF8StringEnumerator</code> - enumerators for strings
</li></ul>
<h4 name="Obsolete_arrays_.2F_enumerators"> Obsolete arrays / enumerators </h4>
<p>There are some deprecated classes which <b>should not be used by new code</b>.
</p>
<ul><li> <code>nsISupportsArray</code> - obsoleted by <code><a href="#nsIArray_.2F_nsIMutableArray">nsIArray</a></code>, use that instead.
</li><li> <code>nsIEnumerator</code> - obsoleted by <code>nsISimpleEnumerator</code>, use that instead.
</li><li> <code>nsIBidirectionalEnumerator</code> - obsoleted by <code>nsISimpleEnumerator</code>, use that instead.
</li><li> <code>nsVoidArray</code> - <code>nsTArray<span class="nowiki">&lt;T&gt;</span></code> is preferred. Using <code>nsAutoVoidArray</code> is still ok, since that saves an allocation over using <code>nsTArray<span class="nowiki">&lt;T&gt;</span>(8)</code>.
</li></ul>
<h2 name="Which_Array_should_I_use.3F"> Which Array should I use? </h2>
<p>Do not use <code>nsISupportsArray</code>; it is deprecated.
</p><p>Does your array need to be scriptable?
If so, use <code>nsIArray</code>.
</p><p>Example: an array attribute in an IDL file would be <code>nsIArray</code>.
</p><p>Will your array store non-refcounted objects and need automatic resizing?
If so, use <code>nsTArray<span class="nowiki">&lt;T&gt;</span></code>.
</p><p>Example: an array of integers or an array of strings.
</p><p>Will your array store non-refcounted objects and be a fixed size?
If so, just use a native C++ array unless you need the enumeration options on <code>nsTArray<span class="nowiki">&lt;T&gt;</span></code>.
</p><p>Example: an array of error message static const char* pointers.
</p><p>Are all the things you are storing interface pointers to instances of the same interface?
If so, use <code>nsCOMArray</code>.
</p><p>Example: a content node's list of <code>nsIContent</code> children.
</p><p>Otherwise use <code>nsIArray</code> and make liberal use of <code>QueryElementAt()</code>.
</p><p>The point of <code>nsCOMArray</code> is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be able to use it because you get type-safety and don't have to spend time and code QIing (like you have to with <code>nsIArray</code>).
</p>
<h2 name="Array_Guidelines"> Array Guidelines </h2>
<p>Here are a few simple rules which will keep your code clean and your developers happy:
</p>
<ul><li> Use typesafe arrays like <code>nsCOMArray<span class="nowiki">&lt;T&gt;</span></code> <code>nsTArray<span class="nowiki">&lt;T&gt;</span></code> wherever possible.
</li><li> Avoid all obsolete arrays and enumerators.
</li><li> Avoid creating temporary arrays.
</li></ul>
<h2 name="Scriptable_Arrays"> Scriptable Arrays </h2>
<h3 name="nsIArray_.2F_nsIMutableArray"> nsIArray / nsIMutableArray </h3>
<h4 name="Usage"> Usage </h4>
<p><code>nsIArray</code> is useful if you need to pass arrays of COM objects through interfaces or require a scriptable array. It can hold strong or weak references to its container objects. This basic interface only allows querying of existing elements in the array. The methods that modify the array have been broken out into <code>nsIMutableArray</code>.
</p><p>An <code>nsIArray</code> implementation can be created from C++ or JavaScript using <a href="en/NsIComponentManager/createInstance">createInstance</a> and the <a href="en/Creating_XPCOM_Components/An_Overview_of_XPCOM#Contract_ID">contract ID</a> "@mozilla.org/array;1". The created array implements <code><a href="en/NsIMutableArray">nsIMutableArray</a></code> and <code><a href="en/NsIArray">nsIArray</a></code>. Since <code>nsIMutableArray</code> derives from <code>nsIArray</code>, the resulting array can be cast to a read-only array. </p><p>C++ Example
</p>
<pre class="eval">void GetList(nsIArray** aResult) {
  nsCOMPtr&lt;nsIMutableArray&gt; array = do_CreateInstance(NS_ARRAY_CONTRACTID);

  // append some elements
  ...

  // return it to the caller
  *aResult = array;
  NS_ADDREF(*aResult);
}
</pre>
<p>JavaScript Example
</p>
<pre class="eval">function getList() {
  var array = Components.classes["@mozilla.org/array;1"]
                        .createInstance(Components.interfaces.nsIMutableArray);
  // append some elements
  ...

  // return it to the caller
  return array;
}
</pre>
<h4 name="Access_to_elements"> Access to elements </h4>
<p>Since <code>nsIArray</code> is a regular XPCOM object, its interfaces follows the standard conventions of ownership. Access to specific elements is through <code>QueryElementAt</code>, which is similar to <code>QueryInterface</code>, but it takes a specific index.
</p>
<pre class="eval">void NotifyObservers(nsIArray* aArray) {
  PRUint32 length;
  aArray-&gt;GetLength(&amp;length);
  for (PRUint32 i=0; i&lt;length; ++i) {
    nsCOMPtr&lt;nsIMyObserver&gt; element;
    aArray-&gt;QueryElementAt(i, NS_GET_IID(nsIElement),
                                getter_AddRefs(element));
    element-&gt;Observe();
  }
}
</pre>
<p>A simpler option is to use the helper <code>do_QueryElementAt</code> which is typesafe.
</p>
<pre class="eval">void NotifyObservers(nsIArray* aArray) {
  PRUint32 length;
  aArray-&gt;GetLength(&amp;length);
  for (PRUint32 i=0; i&lt;length; ++i) {
    nsCOMPtr&lt;nsIMyObserver&gt; element =
    do_QueryElementAt(aArray, i);
     element-&gt;Observe();
  }
}
</pre>
<h4 name="Passing_as_a_parameter"> Passing as a parameter </h4>
<p>Since <code>nsIArray</code> is an XPCOM object, it should be passed as a pointer. To distinguish between read-only arrays and writable arrays, you should make sure to pass a nsIArray or <code>nsIMutableArray</code> as appropriate.
</p><p>When the array can or should be modified, then use nsIMutableArray:
</p>
<pre class="eval">// array is read-only because it uses nsIArray
void PrintSize(nsIArray* elements) {
  PRUint32 count;
  elements-&gt;GetLength(&amp;count);
  printf("There are %d elements.\n", count);
}

// using nsIMutableArray, so callee may modify
void TweakArray(nsIMutableArray* elements) {
  elements-&gt;RemoveElementAt(0);
  elements-&gt;AppendElement(newElement, PR_FALSE);
}
</pre>
<p>While it is usually possible to call <code>QueryInterface</code> on an <code>nsIArray</code> to get access to the <code>nsIMutableArray</code> interface, this is against convention and it should be avoided.
</p>
<pre class="eval">// no need for the double-pointer, and this violates XPCOM rules
// which expect acess to a new object
void TweakArray(nsIMutableArray** elements) {
  // ugh, extra indirection!
  *elements-&gt;RemoveElementAt(0);
  *elements-&gt;AppendElement(newElement, PR_FALSE);
}
</pre>
<h4 name="In-place_enumeration_2"> In-place enumeration </h4>
<p>When accessing all members of an <code>nsIArray</code>, in-place enumeration is preferred over indexed access. However, I seem to have forgotten to implement that. Good thing the interface is under review. Sorry! </p>
<h4 name="Enumerators_2"> Enumerators </h4>
<p>Creating an enumerator from an <code>nsIArray</code> is easy. The method <code>Enumerate()</code> returns a <code>nsISimpleEnumerator</code> which accesses all the elements in the array. Often, simply accessing an array by index, using <code>QueryElementAt</code> is faster. See the section on Enumerators to learn when to properly use enumerators.
</p><p>For example, if you need to iterate an array returned from another object, you might use <code>Enumerate()</code>. </p>
<pre class="eval">...
// get the array
nsCOMPtr&lt;nsIArray&gt; array;
foo-&gt;GetElements(getter_AddRefs(array));

// make an enumerator
nsCOMPtr&lt;nsISimpleEnumerator&gt; enumerator;
array-&gt;Enumerate(getter_AddRefs(enumerator));

// now enumerate the elements
...
</pre>
<h2 name="Typesafe_Arrays"> Typesafe Arrays </h2>
<h3 name="nsCOMArray.3CT.3E"> nsCOMArray&lt;T&gt; </h3>
<p><code>nsCOMArray&lt;T&gt;</code> is a typesafe wrapper around <code>nsVoidArray</code>, so it has a similar API. It enforces both typesafety and XPCOM reference counting by keeping an owning reference to each element in the array.
</p>
<h4 name="Usage_2"> Usage </h4>
<p>It is most often used as a member of a C++ class to store a list of well-typed XPCOM objects. It is also usually declared as an inline member rather than a pointer. As a class member, <code>nsCOMArray&lt;T&gt;</code> is preferred over <code>nsIArray</code> when access to the array is confined to the class itself.
</p><p>For example, here is its use in a class:
</p>
<pre class="eval">class NodeContainer {
public:
  void AddNode(nsINode* node);
   
private:
  nsCOMArray&lt;nsINode&gt; mNodes;
};

// typesafety of mNodes ensures that we only append an nsINode*
void NodeContainer::AddNode(nsINode* node) {
  mNodes.AppendObject(node);
}
   
</pre>
<p><code>nsCOMArray&lt;T&gt;</code> can also be declared on the stack to collect a temporary list of objects and manipulate them. When the object goes out of scope, all its members are released.
</p>
<pre class="eval">void ProcessVisibleItems()
{
  // temporary stack-based nsCOMArray
  nsCOMArray&lt;nsIFoo&gt; fooItems;
  GetCompleteList(fooItems);
   
  // now filter out non visible objects
  // doing this backwards
  PRUint32 i = fooItems.Count();
  while (i &gt; 0) {
    --i;
    PRBool isVisible;
    fooItems[i]-&gt;GetIsVisible(&amp;isVisible);
    if (!isVisible) {
      fooItems.RemoveObjectAt(i);
    }
  }

  // now deal with the processed list
  ProcessList(fooItems);

  // fooItems will release all its members
  // when it goes out of scope
}
</pre>
<h4 name="Access_to_elements_2"> Access to elements </h4>
<p><code>nsCOMArray&lt;T&gt;</code> is a concrete C++ class, and so the [] operator is used to access its members. When using the [] operator, the reference count is unchanged. This allows direct processing of array elements without worrying about calling <code>Release()</code>.
</p><p>For example, this code calls the same method on each member:
</p>
<pre class="eval">void NotifyObservers(const nsCOMArray&lt;nsIMyObserver&gt;&amp; observers) {
  // Using [] doesn't leak!
  for (PRInt32 i = observers.Count() - 1; i &gt;= 0 ; i--)
    observers[i]-&gt;Observe();
}
</pre>
<p>Be careful with this though, you could end up with a weak pointer if you're converting from non-nsCOMArray code.
</p>
<pre class="eval">// old version, relied on automatic addref
// mElements is an nsISupportsArray*
void GetFirstObject(nsIElement** aResult) {
  // no need to call NS_ADDREF - this does it for you
  mElements-&gt;QueryElementAt(0, NS_GET_IID(nsIElement),
  (void**)aResult);
}
  
// new version, make sure to call NS_ADDREF()
// mElements is now a nsCOMArray&lt;nsIElement&gt;
void GetFirstObject(nsIElement** aResult) {
  *aResult = mElements[0];
  NS_ADDREF(*aResult);
}
</pre>
<h4 name="Passing_as_a_parameter_2"> Passing as a parameter </h4>
<p>When passing <code>nsCOMArray&lt;T&gt;</code> among functions, the convention is to pass by reference. Also be sure to use const if you want to enforce that the array is read-only.
</p><p>Here is an example with a read-only and a writable array:
</p>
<pre class="eval">// array is read-only because of const
void PrintSize(const nsCOMArray&lt;nsIElements&gt;&amp; elements) {
 printf("There are %d elements.\n", elements.Count());
}

// no const, so we can modify the array
void TweakArray(nsCOMArray&lt;nsIElement&gt;&amp; elements, nsIElement* newElement) {
  elements.RemoveObjectAt(0);
  elements.AppendObject(newElement);
}
</pre>
<h4 name="In-place_enumeration_3"> In-place enumeration </h4>
<p>The callback-based enumeration in <code>nsCOMArray&lt;T&gt;</code> is about as fast as, if not faster than, standard loop-based iteration. The callback mechanism can be useful when integrating with existing callback-style code however.
</p><p>One particularly nice thing about the callback mechanism is that it is typesafe. For instance:
</p>
<pre class="eval">PR_CALLBACK PRBool getFirstVisible(nsIElement* element, void* closure)   {
 PRBool isVisible;
 element-&gt;IsVisible(&amp;isVisible);

 // stop at first object
 if (isVisible) {
  NS_STATIC_CAST(ClosureObject*,closure)-&gt;element = element;
  return PR_FALSE;
 }
 return PR_TRUE;
}

...
// enumerate to find the object
ClosureObject closureObject = { 0 };
if (!mElements.EnumerateForwards(getFirstVisible, closureObject))
             processElement(closureObject-&gt;element);
...
</pre>
<h4 name="Enumerators_3"> Enumerators </h4>
<p>A <code>nsISimpleEnumerator</code> can be created to provide access to a <code>nsCOMArray&lt;T&gt;</code>. When the enumerator is created, it takes a snapshot of the elements in the array, so that the enumerator can outlive the array.
</p><p>To create the enumerator, use <code>NS_NewArrayEnumerator(nsISimpleEnumerator**, const nsCOMArray&lt;T&gt;&amp;)</code>. For example:
</p>
<pre class="eval">// mElements is an nsCOMArray&lt;nsIElement&gt;
nsFoo::GetElements(nsISimpleEnumerator** aResult) {
  return NS_NewArrayEnumerator(aResult, mElements);
}
</pre>
<h3 name="nsTArray.3CT.3E"> nsTArray&lt;T&gt; </h3>
<p><code>nsTArray&lt;T&gt;</code> is a typesafe array for holding various objects. It can be used to hold objects directly, not just pointers to objects.
</p>
<h4 name="Usage_3"> Usage </h4>
<p>It is most often used as a member of a C++ class to store a list of well-typed objects. It is also usually declared as an inline member rather than a pointer. As a class member, <code>nsTArray&lt;T&gt;</code> is preferred over <code>nsVoidArray</code>.
</p><p>For example, here is its use in a class:
</p>
<pre class="eval">class MediaList {
public:
  void AddMedium(const nsString&amp; aMedium);
   
private:
  nsTArray&lt;nsString&gt; mMedia;
};

// typesafety of mMedia ensures that we only append an nsString
void NodeContainer::AddMedium(const nsString&amp; aMedium) {
  mMedia.AppendElement(aMedium);
}
   
</pre>
<p><code>nsTArray&lt;T&gt;</code> can also be declared on the stack to collect a temporary list of objects and manipulate them. When the object goes out of scope, all its members have their destructors called. Note that if the <code>nsTArray&lt;T&gt;</code> holds pointers to objects, the objects will not be deleted (and hence not have their destructors called).
</p>
<pre class="eval">void ProcessVisibleItems()
{
  // temporary stack-based nsTArray
  nsTArray&lt;FooStruct&gt; fooItems;
  GetCompleteList(fooItems);
   
  // now filter out non visible objects
  // doing this backwards
  PRUint32 i = fooItems.Length();
  while (i &gt; 0) {
    --i;
    PRBool isVisible;
    fooItems[i]-&gt;GetIsVisible(&amp;isVisible);
    if (!isVisible) {
      fooItems.RemoveElementAt(i);
    }
  }

  // now deal with the processed list
  ProcessList(fooItems);

  // fooItems will call the destructors of all the FooStruct objects
  // when it goes out of scope
}
</pre>
<h4 name="Access_to_elements_3"> Access to elements </h4>
<p><code>nsTArray&lt;T&gt;</code> is a concrete C++ class, and so the [] operator is used to access its members.
</p><p>For example, this code calls the same method on each member:
</p>
<pre class="eval">void NotifyObservers(const nsTArray&lt;ObserverClass*&gt;&amp; observers) {
  for (PRUint32 i = observers.Length(); i &gt; 0 ; ) {
    --i;
    observers[i]-&gt;Observe();
  }
}
</pre>
<h4 name="Passing_as_a_parameter_3"> Passing as a parameter </h4>
<p>When passing <code>nsTArray&lt;T&gt;</code> among functions, the convention is to pass by reference. Also be sure to use <code>const</code> if you want to enforce that the array is read-only.
</p><p>Here is an example with a read-only and a writable array:
</p>
<pre class="eval">// array is read-only because of const
void PrintSize(const nsTArray&lt;nsElement&gt;&amp; elements) {
 printf("There are %d elements.\n", elements.Length());
}

// no const, so we can modify the array
void TweakArray(nsTArray&lt;nsElement&gt;&amp; elements, 
                const nsElement&amp; newElement) {
  elements.RemoveElementAt(0);
  elements.AppendElement(newElement);
}
</pre>
<h4 name="In-place_enumeration_4"> In-place enumeration </h4>
<p>There are no enumerator objects that work on an <code>nsTArray&lt;T&gt;</code>.
</p>
<h2 name="C.2B.2B_Arrays"> C++ Arrays </h2>
<h3 name="nsVoidArray"> nsVoidArray </h3>
<p><code>nsVoidArray</code> is a concrete C++ class that allows for storage of any arbitrary object. The base type for all objects is void *. When converting to/from a void *, use <code>NS_STATIC_CAST</code> to ensure that no const-ness is lost.
</p><p>Note that <code>nsVoidArray</code> defines no semantics of ownership of its objects. Depending on its use, the array may either own the objects that it points to, or its member may be pointers to existing objects that are owned by another data structure. Because nsVoidArray itself does not define any ownership rules, it is up to the consumer to know when it is appropriate to free objects out of the array.
</p><p>This implies that when an <code>nsVoidArray</code> goes out of scope, seperate code must free any memory that is semantically owned by the array. This should always be documented in the declaration of the array instance.
</p><p><code>nsCOMArray&lt;T&gt;</code> was designed to eliminate some of the overhead of using nsVoidArray when using COM objects. If your code is using <code>nsVoidArray</code> to keep references to COM objects, consider converting it to <code>nsCOMArray&lt;T&gt;</code>.
</p>
<h4 name="Usage_4"> Usage </h4>
<p><code>nsVoidArray</code> is often used as a member variable in a class. Remember to document ownership!
</p>
<pre class="eval">struct FooElement {
 ...
};

class nsFoo : nsIFoo {
 ...
 virtual ~nsFoo();
 ...
 
 private:
 // mElements owns a list of FooElement structs,
 // which must be deleted when this object goes away
 nsVoidArray mElements;

 // mVisibleElements contains weak (non-owning) references
 // to elements in mElements, and does not need to be cleaned up
 nsVoidArray mVisibleElements;
};

nsFoo::~nsFoo() {
 // mVisibleElements is fine, but
 // don't forget to clean up mElements!
 PRUint32 i, count = mElements.Count();
 for (i=0; i&lt;count; ++i)
  delete NS_STATIC_CAST(FooElement*, mElements[i]);
 }
   
</pre>
<p>As you can see, <code>nsVoidArray</code> has some context-specific overhead to make sure memory is cleaned up appropriately.
</p>
<h4 name="Access_to_elements_4"> Access to elements </h4>
<p>The [] operator is used to access member variables. Don't forget to use <code>NS_STATIC_CAST()</code>.
</p>
<pre class="eval">for (i=0; i&lt;count; ++i) {
 FooElement* element = NS_STATIC_CAST(FooElement*,mElements[i]);
 // now manipulate element
}
   
</pre>
<h4 name="Passing_as_a_parameter_4"> Passing as a parameter </h4>
<p>Like other concrete C++ classes, passing by reference using the &amp; syntax is preferred.
</p>
<h4 name="In-place_enumeration_5"> In-place enumeration </h4>
<h4 name="Enumerators_4"> Enumerators </h4>
<h3 name="nsStringArray_.2F_nsCStringArray"> nsStringArray / nsCStringArray </h3>
<h4 name="Usage_5"> Usage </h4>
<h4 name="Access_to_elements_5"> Access to elements </h4>
<h4 name="Passing_as_a_parameter_5"> Passing as a parameter </h4>
<h4 name="In-place_enumeration_6"> In-place enumeration </h4>
<h4 name="Enumerators_5"> Enumerators </h4>
<h3 name="nsAutoVoidArray"> nsAutoVoidArray </h3>
<h4 name="Usage_6"> Usage </h4>
<h4 name="Access_to_elements_6"> Access to elements </h4>
<h4 name="Passing_as_a_parameter_6"> Passing as a parameter </h4>
<h4 name="In-place_enumeration_7"> In-place enumeration </h4>
<h4 name="Enumerators_6"> Enumerators </h4>
<h3 name="nsSmallVoidArray"> nsSmallVoidArray </h3>
<h4 name="Usage_7"> Usage </h4>
<h4 name="Access_to_elements_7"> Access to elements </h4>
<h4 name="Passing_as_a_parameter_7"> Passing as a parameter </h4>
<h4 name="In-place_enumeration_8"> In-place enumeration </h4>
<h4 name="Enumerators_7"> Enumerators </h4>
<h2 name="Enumerators_8"> Enumerators </h2>
<p>Enumerators are very simple, structure-free objects for visiting each member of a set of objects. The enumerators are used as a generic interface for arrays, hashtables, and other constructs which contain one or more objects. When designing public interfaces, enumerators are the preferred mechanism for accessing these structures because they hide the details of the implementation behind the interface.
</p>
<h3 name="nsISimpleEnumerator"> nsISimpleEnumerator </h3>
<p><code>nsISimpleEnumerator</code> is a generic enumerator for enumerating a list of any XPCOM object. There are many implementations of <code>nsISimpleEnumerator</code>, including one that enumerates <code>nsIArray</code> objects, and another one for <code>nsCOMArray</code>. It is very common for other interfaces which support <code>nsISimpleEnumerator</code> to make their own implementations.
</p>
<h3 name="nsIStringEnumerator"> nsIStringEnumerator </h3>
<p>String enumerators provide an easy way to pass a list of strings around with minimal copying. Both unicode strings and UTF8-encoded strings are supported. For more information about the different types of strings, see the String Guide.
</p><p>String enumerators can be created from <code>nsStringArray</code> or <code>nsCStringArray</code> objects. The implementation of the string enumerator interfaces for <code>nsStringArray</code> and <code>nsCStringArray</code> supports conversion between UTF8 and Unicode, and can be QueryInterface'd back and forth between <code>nsIStringEnumerator</code> and <code>nsIUTF8StringEnumerator</code>.
</p><p>To create an nsIStringEnumerator for an <code>nsStringArray</code>, you can use one of the variations of <code>NS_NewStringEnumerator</code>. There are also corresponding enumerators and helpers for UTF8 strings. In the examples below, <code>NS_NewUTF8StringEnumerator</code> can be used along with <code>nsIUTF8StringEnumerator</code> and <code>nsCStringArray</code>.
</p><p>This first example demonstrates the case where a class which owns an <code>nsStringArray</code>, and are returns an <code>nsIStringEnumerator</code> to a caller. You can use the variation of <code>NS_NewStringEnumerator</code> that ensures the owner of the array outlives the enumerator. This is necessary because nsStringArray is not reference counted. Without holding a reference to the owner, the enumerator could be left with a dangling pointer to a deleted <code>nsStringArray</code>. </p>
<pre class="eval">class nsFoo : nsIFoo {
...
private:
  nsStringArray mElementNames;
};

nsFoo::GetElementNames(nsIStringEnumerator** aResult)
{
  // pass in "this" to make sure the enumerator
  // holds a reference to "this"
  return NS_NewStringEnumerator(aResult, mElementNames, this);
}
</pre>
<p>One variant of <code>NS_NewStringEnumerator</code> does not require an owner, but should only be used when the lifetime of the enumerator is known to be shorter than that of the array. Often this is used when a method must take a <code>nsIStringEnumerator</code> rather than an <code>nsStringArray</code>, due to some sort of interface constraint.
</p>
<pre class="eval">class nsFoo : nsIFoo {
 ...
 // when ProcessElements returns, the enumerator is at the
 // end of the list, and can be released.
 NS_IMETHODIMP ProcessNames(nsIStringEnumerator*);
 private:
   
 nsStringArray mElementNames;
};

...
nsCOMPtr&lt;nsIStringEnumerator&gt; enumerator;
NS_NewStringEnumerator(getter_AddRefs(enumerator), mElementNames);

// now call a method on "this" that has a known behavior
ProcessNames(enumerator);
// now enumerator is used up, and can be released
...
</pre>
<p>The last version of <code>nsIStringEnumerator</code> takes ownership of an <code>nsStringArray</code> and is responsible for freeing the array when the enumerator is used up.
</p>
<pre class="eval">void GetNames(nsIStringEnumerator** aResult)
{
 nsStringArray *resultArray = new nsStringArray;
 resultArray-&gt;AppendString(str1);
 resultArray-&gt;AppendString(str2);
 
 // enumerator will free resultArray
 return NS_NewAdoptingStringEnumerator(aResult, resultArray);
}
</pre>
<p>As noted above, these implementations of <code>nsIStringEnumerator</code> can also be QueryInterface'd between nsIStringEnumerator and <code>nsIUTF8StringEnumerator</code>. The implementations will properly convert back and forth between UTF8 and Unicode. To ensure that you get the right implementation and the conversion is done in the right direction, make sure that you call the version of <code>NS_NewStringEnumerator</code> or <code>NS_NewUTF8StringEnumerator</code> that corresponds to the array type, not the enumerator type.
</p><p>For example, if a class has an internal <code>nsCStringArray</code> of UTF8 strings, but needs to implement an interface which returns an nsIStringEnumerator, it should use <code>NS_NewStringEnumerator</code>: </p>
<pre class="eval">class nsFoo : nsIFoo {
 ...
 NS_IMETHOD GetStrings(nsIStringEnumerator** aResult);
</pre>
<pre class="eval"> private:
 nsCStringArray mElementNames;
};

NS_IMETHODIMP
nsFoo::GetStrings(nsIStringEnumerator** aResult) {
 nsresult rv;
 nsCOMPtr&lt;nsIUTF8StringEnumerator&gt; enumerator
 rv = NS_NewUTF8StringEnumerator(getter_AddRefs(enumerator),
                                       mElementNames, this);
 return CallQueryInterface(enumerator, aResult);
}
</pre>
<h2 name="Obsolete_Arrays_and_Enumerators"> Obsolete Arrays and Enumerators </h2>
<h3 name="nsISupportsArray"> nsISupportsArray </h3>
<h3 name="nsIEnumerator_.28includes_nsIBidirectionalEnumerator.29"> nsIEnumerator (includes nsIBidirectionalEnumerator) </h3>
Revert to this revision