ArrayList.Item[Int32] 속성

정의

지정한 인덱스에 있는 요소를 가져오거나 설정합니다.

public:
 virtual property System::Object ^ default[int] { System::Object ^ get(int index); void set(int index, System::Object ^ value); };
public virtual object this[int index] { get; set; }
public virtual object? this[int index] { get; set; }
member this.Item(int) : obj with get, set
Default Public Overridable Property Item(index As Integer) As Object

매개 변수

index
Int32

가져오거나 설정할 요소의 인덱스(0부터 시작)입니다.

속성 값

지정한 인덱스의 요소입니다.

구현

예외

index가 0보다 작은 경우

또는

indexCount보다 크거나 같은 경우

예제

다음 코드 예제에서는 를 만들고 ArrayList 여러 항목을 추가합니다. 이 예제에서는 속성(C#의 인덱서)을 Item[] 사용하여 요소에 액세스하고 지정된 인덱스에 대한 속성에 새 값을 할당하여 요소를 변경하는 방법을 Item[] 보여 줍니다. 또한 이 예제에서는 속성이 목록의 Item[] 현재 크기 외부에 있는 요소에 액세스하거나 추가하는 데 사용할 수 없음을 보여줍니다.

using namespace System;
using namespace System::Collections;

public ref class Example
{
public:
    static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ArrayList^ stringList = gcnew ArrayList();

        stringList->Add("a");
        stringList->Add("abc");
        stringList->Add("abcdef");
        stringList->Add("abcdefg");

        // The Item property is an indexer, so the property name is
        // not required.
        Console::WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Assigning a value to the property changes the value of
        // the indexed element.
        stringList[2] = "abcd";
        Console::WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Accessing an element outside the current element count
        // causes an exception.
        Console::WriteLine("Number of elements in the list: {0}", 
            stringList->Count);
        try
        {
            Console::WriteLine("Element {0} is \"{1}\"", 
                stringList->Count, stringList[stringList->Count]);
        }
        catch (ArgumentOutOfRangeException^ aoore)
        {
            Console::WriteLine("stringList({0}) is out of range.", 
                stringList->Count);
        }

        // You cannot use the Item property to add new elements.
        try
        {
            stringList[stringList->Count] = "42";
        }
        catch (ArgumentOutOfRangeException^ aoore)
        {
            Console::WriteLine("stringList({0}) is out of range.", 
                stringList->Count);
        }

        Console::WriteLine();
        for (int i = 0; i < stringList->Count; i++)
        {
            Console::WriteLine("Element {0} is \"{1}\"", i, 
                stringList[i]);
        }

        Console::WriteLine();
        for each (Object^ o in stringList)
        {
            Console::WriteLine(o);
        }
    }
};

int main()
{
   Example::Main();
}
/*
 This code example produces the following output:

Element 2 is "abcdef"
Element 2 is "abcd"
Number of elements in the list: 4
stringList(4) is out of range.
stringList(4) is out of range.

Element 0 is "a"
Element 1 is "abc"
Element 2 is "abcd"
Element 3 is "abcdefg"

a
abc
abcd
abcdefg
 */
using System;
using System.Collections;

public class Example
{
    public static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ArrayList stringList = new ArrayList();

        stringList.Add("a");
        stringList.Add("abc");
        stringList.Add("abcdef");
        stringList.Add("abcdefg");

        // The Item property is an indexer, so the property name is
        // not required.
        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Assigning a value to the property changes the value of
        // the indexed element.
        stringList[2] = "abcd";
        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Accessing an element outside the current element count
        // causes an exception.
        Console.WriteLine("Number of elements in the list: {0}",
            stringList.Count);
        try
        {
            Console.WriteLine("Element {0} is \"{1}\"",
                stringList.Count, stringList[stringList.Count]);
        }
        catch(ArgumentOutOfRangeException aoore)
        {
            Console.WriteLine("stringList({0}) is out of range.",
                stringList.Count);
        }

        // You cannot use the Item property to add new elements.
        try
        {
            stringList[stringList.Count] = "42";
        }
        catch(ArgumentOutOfRangeException aoore)
        {
            Console.WriteLine("stringList({0}) is out of range.",
                stringList.Count);
        }

        Console.WriteLine();
        for (int i = 0; i < stringList.Count; i++)
        {
            Console.WriteLine("Element {0} is \"{1}\"", i,
                stringList[i]);
        }

        Console.WriteLine();
        foreach (object o in stringList)
        {
            Console.WriteLine(o);
        }
    }
}
/*
 This code example produces the following output:

Element 2 is "abcdef"
Element 2 is "abcd"
Number of elements in the list: 4
stringList(4) is out of range.
stringList(4) is out of range.

Element 0 is "a"
Element 1 is "abc"
Element 2 is "abcd"
Element 3 is "abcdefg"

a
abc
abcd
abcdefg
 */
Imports System.Collections

Public Class Example

    Public Shared Sub Main

        ' Create an empty ArrayList, and add some elements.
        Dim stringList As New ArrayList

        stringList.Add("a")
        stringList.Add("abc")
        stringList.Add("abcdef")
        stringList.Add("abcdefg")

        ' Item is the default property, so the property name is
        ' not required.
        Console.WriteLine("Element {0} is ""{1}""", 2, stringList(2))

        ' Assigning a value to the property changes the value of
        ' the indexed element.
        stringList(2) = "abcd"
        Console.WriteLine("Element {0} is ""{1}""", 2, stringList(2))

        ' Accessing an element outside the current element count
        ' causes an exception. The ArrayList index is zero-based,
        ' so the index of the last element is (Count - 1). 
        Console.WriteLine("Number of elements in the list: {0}", _
            stringList.Count)
        Try
            Console.WriteLine("Element {0} is ""{1}""", _
                stringList.Count, _
                stringList(stringList.Count))
        Catch aoore As ArgumentOutOfRangeException
            Console.WriteLine("stringList({0}) is out of range.", _
                stringList.Count)
        End Try

        ' You cannot use the Item property to add new elements.
        Try
            stringList(stringList.Count) = "42"
        Catch aoore As ArgumentOutOfRangeException
            Console.WriteLine("stringList({0}) is out of range.", _
                stringList.Count)
        End Try

        Console.WriteLine()
        For i As Integer = 0 To stringList.Count - 1
            Console.WriteLine("Element {0} is ""{1}""", i, stringList(i))
        Next

        Console.WriteLine()
        For Each o As Object In stringList
            Console.WriteLine(o)
        Next

    End Sub

End Class
'
' This code example produces the following output:
'
'Element 2 is "abcdef"
'Element 2 is "abcd"
'Number of elements in the list: 4
'stringList(4) is out of range.
'stringList(4) is out of range.
'
'Element 0 is "a"
'Element 1 is "abc"
'Element 2 is "abcd"
'Element 3 is "abcdefg"
'
'a
'abc
'abcd
'abcdefg

다음 예제에서는 속성을 명시적으로 사용하여 Item[] 목록의 항목에 값을 할당합니다. 이 예제에서는 를 상속하는 클래스를 ArrayList 정의하고 목록 항목을 스크램블링하는 메서드를 추가합니다.

using namespace System;
using namespace System::Collections;

public ref class ScrambleList : public ArrayList
{
public:
    static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ScrambleList^ integerList = gcnew ScrambleList();

        for (int i = 0; i < 10; i++)
        {
            integerList->Add(i);
        }

        Console::WriteLine("Ordered:\n");
        for each (int value in integerList)
        {
            Console::Write("{0}, ", value);
        }
        Console::WriteLine("<end>\n\nScrambled:\n");

        // Scramble the order of the items in the list.
        integerList->Scramble();

        for each (int value in integerList)
        {
            Console::Write("{0}, ", value);
        }
        Console::WriteLine("<end>\n");
    }

    void Scramble()
    {
        int limit = this->Count;
        int temp;
        int swapindex;
        Random^ rnd = gcnew Random();
        for (int i = 0; i < limit; i++)
        {
            // The Item property of ArrayList is the default indexer. Thus,
            // this->default[i] and this[i] are used interchangeably.
            temp = (int)this->default[i];
            swapindex = rnd->Next(0, limit - 1);
            this[i] = this->default[swapindex];
            this[swapindex] = temp;
        }
    }
};

int main()
{
    ScrambleList::Main();
}
// The program produces output similar to the following:
//
// Ordered:
//
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, <end>
//
// Scrambled:
//
// 5, 2, 8, 9, 6, 1, 7, 0, 4, 3, <end>
using System;
using System.Collections;

public class ScrambleList : ArrayList
{
    public static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ScrambleList integerList = new ScrambleList();

        for (int i = 0; i < 10; i++)
        {
            integerList.Add(i);
        }

        Console.WriteLine("Ordered:\n");
        foreach (int value in integerList)
        {
            Console.Write("{0}, ", value);
        }
        Console.WriteLine("<end>\n\nScrambled:\n");

        // Scramble the order of the items in the list.
        integerList.Scramble();

        foreach (int value in integerList)
        {
            Console.Write("{0}, ", value);
        }
        Console.WriteLine("<end>\n");
    }

    public void Scramble()
    {
        int limit = this.Count;
        int temp;
        int swapindex;
        Random rnd = new Random();
        for (int i = 0; i < limit; i++)
        {
            // The Item property of ArrayList is the default indexer. Thus,
            // this[i] is used instead of Item[i].
            temp = (int)this[i];
            swapindex = rnd.Next(0, limit - 1);
            this[i] = this[swapindex];
            this[swapindex] = temp;
        }
    }
}

// The program produces output similar to the following:
//
// Ordered:
//
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, <end>
//
// Scrambled:
//
// 5, 2, 8, 9, 6, 1, 7, 0, 4, 3, <end>
Imports System.Collections

Public Class ScrambleList
    Inherits ArrayList

    Public Shared Sub Main()
        ' Create an empty ArrayList, and add some elements.
        Dim integerList As New ScrambleList()

        For i As Integer = 0 To 9
            integerList.Add(i)
        Next i

        Console.WriteLine("Ordered:" + Environment.NewLine)
        For Each value As Integer In integerList
            Console.Write("{0}, ", value)
        Next value
        Console.WriteLine("<end>" + Environment.NewLine + Environment.NewLine + "Scrambled:" + Environment.NewLine)

        ' Scramble the order of the items in the list.
        integerList.Scramble()

        For Each value As Integer In integerList
            Console.Write("{0}, ", value)
        Next value
        Console.WriteLine("<end>" + Environment.NewLine)
    End Sub

    Public Sub Scramble()
        Dim limit As Integer = MyClass.Count
        Dim temp As Integer
        Dim swapindex As Integer
        Dim rnd As New Random()
        For i As Integer = 0 To limit - 1
            ' The Item property of ArrayList is the default indexer. Thus,
            ' Me(i) and MyClass.Item(i) are used interchangeably.
            temp = CType(Me(i), Integer)
            swapindex = rnd.Next(0, limit - 1)
            MyClass.Item(i) = Me(swapindex)
            MyClass.Item(swapindex) = temp
        Next i
    End Sub
End Class

' The program produces output similar to the following:
'
' Ordered:
'
' 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, <end>
'
' Scrambled:
'
' 5, 2, 8, 9, 6, 1, 7, 0, 4, 3, <end>

설명

Item[]Object반환하므로 반환된 값을 원래 형식으로 캐스팅하여 조작해야 할 수 있습니다. 는 강력한 형식의 컬렉션이 ArrayList 아니라는 점에 유의해야 합니다. 강력한 형식의 대안은 을 참조하세요 List<T>.

ArrayListnull 유효한 값으로 허용되고 중복 요소를 허용합니다.

이 속성은 myCollection[index] 구문을 사용하여 컬렉션의 특정 요소에 액세스하는 기능을 제공합니다.

C# 언어에서는 this 속성을 구현하는 대신 Item[] 키워드를 사용하여 인덱서를 정의합니다. Visual Basic에서는 동일한 인덱싱 기능을 제공하는 Item[]을 기본 속성으로 구현합니다.

이 속성의 값을 검색하는 작업은 작업입니다 O(1) . 속성 설정도 작업입니다 O(1) .

적용 대상

추가 정보