Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Objects, Interfaces, and Patt... > Create a Comparable Object - Pg. 86

86 Microsoft Visual Basic .NET Programmer's Cookbook Dim List As New ArrayList() List.Add("blue") List.Add("green") List.Add("yellow") List.Add("red") ' Remove "blue" by index number. List.RemoveAt(0) ' Remove "green" using a search. List.Remove("green") Console.WriteLine("Items: " & List.Count.ToString()) ' Display ArrayList contents ("yellow" and "red"). Dim Item As String For Each Item In List Console.WriteLine(Item) Next The ArrayList class uses a capacity system similar to the StringBuilder class described in recipe 1.14. When an ArrayList is first created, it allocates an internal buffer for 16 items. If more items are needed, it expands the count by doubling it (to 32, then 64, and so on). If you know how many items an Array- List will contain, you can reserve the required space in advance by specifying it in the ArrayList constructor. This can improve performance slightly. ' Reserve space for 50 elements. Dim List As New ArrayList(50) The ArrayList is weakly typed, which means that it stores everything as a base Object type. When retrieving an item, you need to cast it accordingly. Dim Item As String = CType(List(0), String) This behavior can introduce problems in an application because there's no way to ensure that the wrong type of object isn't added to an array. To solve this problem, you might want to create a custom strongly typed collection, as described in recipe 3.16. Note Microsoft .NET does provide one strongly typed list, although it's easy to overlook: the StringCollection class, which is provided in the System.Collections.Specialized namespace. This class only accepts strings (although duplicate string entries are completely acceptable).