One of the most common operations in programming is the storage of large sets of data. There are databases, of course, which can store any type of data and preserve their structure as well, but not all applications use databases. If your application needs to store custom objects, such as the ones you designed in Chapter, ‘‘Building Custom Classes,’’ or a few names and contact information, you shouldn’t have to set up a database. A simple collection like the ones described in this chapter will suffice.
Traditionally, programmers used arrays to store related data. Because arrays can store custom data types, they seem to be the answer to many data-storage and data-manipulation issues. Arrays, however, don’t expose all the functionality you might need in your application. To address the issues of data storage outside databases, the Framework provides, in addition to arrays, of course, certain classes known as collections.
In this chapter, you’ll learn how to do the following:
- Make the most of arrays – The simplest method of storing sets of data is to use arrays. They’re very efficient and they provide methods to perform advanced operations such as sorting and searching their elements. Use the Sort method of the Array class to sort an array’s elements. To search for an element in an array, use the IndexOf and LastIndexOf methods, or the Binary-Search method if the array is sorted. The BinarySearch method always returns an element’s index, which is a positive value for exact matches and a negative value for near matches.
- Store data in specialized collections such as ArrayLists and HashTables – In addition to arrays, the Framework provides collections, which are dynamic data structures. The most commonly used collections are the ArrayList and the HashTable. ArrayLists are similar to arrays, but they’re dynamic structures. ArrayLists store lists of items, whereas HashTables store key-value pairs and allow you to access their elements via a key. You can add elements by using the Add method and remove existing elements by using the Remove and RemoveAt methods.HashTables provide the ContainsKey and ContainsValue methods to find out whether the collection already contains a specific key or value, and the GetKeys and GetValues methods to retrieve all the keys and values from the collection, respectively.
- Sort and search collections – Collections provide the Sort method for sorting their items and several methods to locate items: IndexOf, LastIndexOf, and BinarySearch. Both sort and search operations are based on comparisons, and the Framework knows how to compare values types only (Integers, Strings, and the other primitive data types). If a collection contains objects, you must provide a custom function that knows how to compare two objects of the same type.