Este tema aún no ha recibido ninguna valoración - Valorar este tema

ArrayList.Insert (Método)

Inserta un elemento en la clase ArrayList en el índice especificado.

Espacio de nombres: System.Collections
Ensamblado: mscorlib (en mscorlib.dll)

public virtual void Insert (
	int index,
	Object value
)
public void Insert (
	int index, 
	Object value
)
public function Insert (
	index : int, 
	value : Object
)

Parámetros

index

Índice basado en cero en el que debe insertarse value.

value

Clase Object que se va a insertar. El valor puede ser referencia de objeto null (Nothing en Visual Basic).

Tipo de excepción Condición

ArgumentOutOfRangeException

index es menor que cero.

O bien

index es mayor que Count.

NotSupportedException

ArrayList es de sólo lectura.

O bien

ArrayList tiene un tamaño fijo.

El objeto ArrayList acepta referencia de objeto null (Nothing en Visual Basic) como valor válido y permite elementos duplicados.

Si la propiedad Count ya es igual a la propiedad Capacity, se aumenta la capacidad de ArrayList reasignando automáticamente la matriz interna y se copian los elementos existentes a la nueva matriz antes de agregar el nuevo elemento.

Si index es igual a Count, se agrega value al final de la clase ArrayList.

En colecciones de elementos contiguos, como listas, los elementos que van a continuación del punto de inserción se desplazan hacia abajo para alojar el elemento nuevo. Si la colección está indizada, los índices de los elementos que se desplazan también se actualizan. Este comportamiento no se aplica a colecciones donde los elementos se agrupan conceptualmente en depósitos, como una tabla hash.

Este método es una operación O(n), donde n es Count.

En el ejemplo de código siguiente se muestra cómo se insertan elementos en ArrayList.

using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList using Insert instead of Add.
      ArrayList myAL = new ArrayList();
      myAL.Insert( 0, "The" );
      myAL.Insert( 1, "fox" );
      myAL.Insert( 2, "jumps" );
      myAL.Insert( 3, "over" );
      myAL.Insert( 4, "the" );
      myAL.Insert( 5, "dog" );

      // Creates and initializes a new Queue.
      Queue myQueue = new Queue();
      myQueue.Enqueue( "quick" );
      myQueue.Enqueue( "brown" );

      // Displays the ArrayList and the Queue.
      Console.WriteLine( "The ArrayList initially contains the following:" );
      PrintValues( myAL );
      Console.WriteLine( "The Queue initially contains the following:" );
      PrintValues( myQueue );

      // Copies the Queue elements to the ArrayList at index 1.
      myAL.InsertRange( 1, myQueue );

      // Displays the ArrayList.
      Console.WriteLine( "After adding the Queue, the ArrayList now contains:" );
      PrintValues( myAL );

      // Search for "dog" and add "lazy" before it.
      myAL.Insert( myAL.IndexOf( "dog" ), "lazy" );

      // Displays the ArrayList.
      Console.WriteLine( "After adding \"lazy\", the ArrayList now contains:" );
      PrintValues( myAL );

      // Add "!!!" at the end.
      myAL.Insert( myAL.Count, "!!!" );

      // Displays the ArrayList.
      Console.WriteLine( "After adding \"!!!\", the ArrayList now contains:" );
      PrintValues( myAL );

      // Inserting an element beyond Count throws an exception.
      try  {
         myAL.Insert( myAL.Count+1, "anystring" );
      } catch ( Exception myException )  {
         Console.WriteLine("Exception: " + myException.ToString());
      }
   }

   public static void PrintValues( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }

}
/* 
This code produces the following output.

The ArrayList initially contains the following:
   The   fox   jumps   over   the   dog
The Queue initially contains the following:
   quick   brown
After adding the Queue, the ArrayList now contains:
   The   quick   brown   fox   jumps   over   the   dog
After adding "lazy", the ArrayList now contains:
   The   quick   brown   fox   jumps   over   the   lazy   dog
After adding "!!!", the ArrayList now contains:
   The   quick   brown   fox   jumps   over   the   lazy   dog   !!!
Exception: System.ArgumentOutOfRangeException: Insertion index was out of range.  Must be non-negative and less than or equal to size.
Parameter name: index
   at System.Collections.ArrayList.Insert(Int32 index, Object value)
   at SamplesArrayList.Main()
*/


import System.*;
import System.Collections.*;

public class SamplesArrayList
{
    public static void main(String[] args)
    {
        // Creates and initializes a new ArrayList using Insert instead of Add.
        ArrayList myAL = new ArrayList();

        myAL.Insert(0, "The");
        myAL.Insert(1, "fox");
        myAL.Insert(2, "jumps");
        myAL.Insert(3, "over");
        myAL.Insert(4, "the");
        myAL.Insert(5, "dog");

        // Creates and initializes a new Queue.
        Queue myQueue = new Queue();

        myQueue.Enqueue("quick");
        myQueue.Enqueue("brown");

        // Displays the ArrayList and the Queue.
        Console.WriteLine("The ArrayList initially contains the following:");
        PrintValues(myAL);
        Console.WriteLine("The Queue initially contains the following:");
        PrintValues(myQueue);

        // Copies the Queue elements to the ArrayList at index 1.
        myAL.InsertRange(1, myQueue);

        // Displays the ArrayList.
        Console.WriteLine("After adding the Queue, the ArrayList now contains:");
        PrintValues(myAL);

        // Search for "dog" and add "lazy" before it.
        myAL.Insert(myAL.IndexOf("dog"), "lazy");

        // Displays the ArrayList.
        Console.WriteLine("After adding \"lazy\", the ArrayList now contains:");
        PrintValues(myAL);

        // Add "!!!" at the end.
        myAL.Insert(myAL.get_Count(), "!!!");

        // Displays the ArrayList.
        Console.WriteLine("After adding \"!!!\", the ArrayList now contains:");
        PrintValues(myAL);

        // Inserting an element beyond Count throws an exception.
        try {
            myAL.Insert(myAL.get_Count() + 1, "anystring");
        }
        catch (System.Exception myException) {
            Console.WriteLine("Exception: " + myException.ToString());
        }
    } //main

    public static void PrintValues(IEnumerable myList)
    {
        IEnumerator objMyEnum = myList.GetEnumerator();
        while (objMyEnum.MoveNext()) {
            Object obj = objMyEnum.get_Current();
            Console.Write("   {0}", obj);
        }
        Console.WriteLine();
    } //PrintValues
} //SamplesArrayList 
/* 
 This code produces the following output.
 
 The ArrayList initially contains the following:
    The   fox   jumps   over   the   dog
 The Queue initially contains the following:
    quick   brown
 After adding the Queue, the ArrayList now contains:
    The   quick   brown   fox   jumps   over   the   dog
 After adding "lazy", the ArrayList now contains:
    The   quick   brown   fox   jumps   over   the   lazy   dog
 After adding "!!!", the ArrayList now contains:
    The   quick   brown   fox   jumps   over   the   lazy   dog   !!!
 Exception: System.ArgumentOutOfRangeException: Insertion index was out of range.  
 Must be non-negative and less than or equal to size.
 Parameter name: index
    at System.Collections.ArrayList.Insert(Int32 index, Object value)
    at SamplesArrayList.main(String[] args)
 */

import System;
import System.Collections;


// Creates and initializes a new ArrayList using Insert instead of Add.
var myAL : ArrayList = new ArrayList();
myAL.Insert( 0, "The" );
myAL.Insert( 1, "fox" );
myAL.Insert( 2, "jumped" );
myAL.Insert( 3, "over" );
myAL.Insert( 4, "the" );
myAL.Insert( 5, "dog" );

// Creates and initializes a new Queue.
var myQueue : Queue = new Queue();
myQueue.Enqueue( "quick" );
myQueue.Enqueue( "brown" );

// Displays the ArrayList and the Queue.
Console.WriteLine( "The ArrayList initially contains the following:" );
PrintValues( myAL );
Console.WriteLine( "The Queue initially contains the following:" );
PrintValues( myQueue );

// Copies the Queue elements to the ArrayList at index 1.
myAL.InsertRange( 1, myQueue );

// Displays the ArrayList.
Console.WriteLine( "After adding the Queue, the ArrayList now contains:" );
PrintValues( myAL );

// Search for "dog" and add "lazy" before it.
myAL.Insert( myAL.IndexOf( "dog" ), "lazy" );

// Displays the ArrayList.
Console.WriteLine( "After adding \"lazy\", the ArrayList now contains:" );
PrintValues( myAL );

// Add "!!!" at the end.
myAL.Insert( myAL.Count, "!!!" );

// Displays the ArrayList.
Console.WriteLine( "After adding \"!!!\", the ArrayList now contains:" );
PrintValues( myAL );

// Inserting an element beyond Count throws an exception.
try  {
  myAL.Insert( myAL.Count+1, "anystring" );
} catch ( myException : Exception )  {
  Console.WriteLine("Exception: " + myException.ToString());
}


 
function PrintValues( myList : IEnumerable)  {
   var  myEnumerator : System.Collections.IEnumerator = myList.GetEnumerator();
   while ( myEnumerator.MoveNext() )
      Console.Write( "\t{0}", myEnumerator.Current );
   Console.WriteLine();
}
 /* 
 This code produces the following output.
 
 The ArrayList initially contains the following:
 	The	fox	jumped	over	the	dog
 The Queue initially contains the following:
 	quick	brown
 After adding the Queue, the ArrayList now contains:
 	The	quick	brown	fox	jumped	over	the	dog
 After adding "lazy", the ArrayList now contains:
 	The	quick	brown	fox	jumped	over	the	lazy	dog
 After adding "!!!", the ArrayList now contains:
 	The	quick	brown	fox	jumped	over	the	lazy	dog	!!!
 Exception: System.ArgumentOutOfRangeException: Insertion index was out of range.  Must be non-negative and less than or equal to size.
 Parameter name: index
    at System.Collections.ArrayList.Insert(Int32 index, Object value)
    at JScript 0.Global Code()
 */ 

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0
¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar