2008年11月9日 星期日

ArrayList 說明例

Module Module1
    Dim aList1 As New ArrayList
    Dim data1() = {1, 2, 5, 10}
    Dim s() = {1, 2, 3, 4, 5, 6, 9, 10}
    Dim aList2 As New ArrayList

    Sub Main()
        '由陣列加入元素
        For i = 0 To 3
            aList1.Add(data1(i))
        Next

        '列出ArrayList元素 方法一
        For Each elm1 In aList1
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '反轉
        aList1.Reverse()

        '列出ArrayList元素 方法二
        For i = 0 To aList1.Count - 1
            Console.WriteLine(aList1(i))
        Next

        '移除元素 -- 指明註標
        aList1.Remove(aList1(0))

        '移除元素 -- 指明元素值
        aList1.Remove(5)
        Console.WriteLine()
        '
        For Each elm1 In aList1
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '插入元素至指定位置
        aList1.Insert(1, 5)
        '
        For Each elm1 In aList1
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '加入元素至最後位置
        aList1.Add(10)

        '
        For Each elm1 In aList1
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '尋找資料在Arraylist中的位置 0:第一個位址 -1:找不到
        For Each elm1 In s
            Dim x = aList1.IndexOf(elm1)
            Console.WriteLine(elm1 & " ->位址:" & x)
        Next
        Console.WriteLine()

        '複製給aList2後,清空aList1
        aList2 = aList1.Clone()
        aList1.Clear()
        For Each elm1 In aList1
            Console.WriteLine(elm1)
        Next

        '排序aList2,再反轉,達成降冪排序目的
        aList2.Sort()
        aList2.Reverse()
        For Each elm1 In aList2
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '拷貝至array1
        Dim array1 = aList2.ToArray
        For Each elm1 In array1
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()

        '以升冪排序後,採用Binary Search ,注意找不到為負值,但不一定是-1
        Console.WriteLine("Binary Search")
        aList2.Sort()
        For Each elm1 In aList2
            Console.WriteLine(elm1)
        Next
        Console.WriteLine()
        For Each elm1 In s
            Dim x = aList2.BinarySearch(elm1)
            Console.WriteLine(elm1 & " ->位址:" & x)
        Next
        Console.WriteLine()

        Console.Read()
    End Sub
End Module 

image

沒有留言: