figure 2.1
output of listing 2.1.1 when viewed through a browser.
adding elements to an arraylist
in listing 2.1.1 we create two arraylist class instances, aterritories and astates, on lines 5 and 6, respectively. we then populate the astates arraylist with a small subset of the 50 states of the united states using the add method (lines 9 through 13). the add method takes one parameter, the element to add to the array, which needs to be of type object. this object instance is then appended to the end of the arraylist. in this example we are simply adding elements of type string to the arraylist astates and aterritories.
the add method is useful for adding one element at a time to the end of the array, but what if we want to add a number of elements to an arraylist at once? the arraylist class provides the addrange method to do just this. addrange expects a single parameter that supports the icollection interface. a wide number of .net framework classes—such as the array, arraylist, dataview, datasetview, and others—support this interface. on line 18 in listing 2.1.1, we use the addrange method to add each element of the astates arraylist to the end of the aterritories arraylist. (to add a range of elements starting at a specific index in an arraylist, use the insertrange method.) on lines 18 and 19, we add two more strings to the end of the aterritories arraylist.
because arraylists are ordered sequentially, there might be times when we want to add an element to a particular position. the insert method of the arraylist class provides this capability, allowing the developer to add an element to a specific spot in the arraylist collection. the insert method takes two parameters: an integer representing the index in which you want to add the new element, and the new element, which needs to be of type object. in line 23 we add a new string to the start of the aterritories arraylist. note that if we had simply used the add method, "district of columbia" would have been added to the end of aterritories. using insert, however, we can specify exactly where in the arraylist this new element should reside.
removing elements from an arraylist
the arraylist class also provides a number of methods for removing elements. we can remove a specific element from an arraylist with the remove method. on line 37 we remove the string "wyoming" from the aterritories arraylist. (if you attempt to remove an element that does not exist, an argumentexception exception will be thrown.) remove allows you to take out a particular element from an arraylist; removeat, used on line 40, allows the developer to remove an element at a specific position in the arraylist.
both remove and removeat dissect only one element from the arraylist at a time. we can remove a chunk of elements in one fell swoop by using the removerange method. this method expects two parameters: an index to start at and a count of total elements to remove. in line 56 we remove the first two elements in aterritories with the statement: aterritories.removerange(0, 2). finally, to remove all the contents of an arraylist, use the clear method (refer to line 69 in listing 2.1.1).
referencing arraylist elements
note that in our code example, we used two different techniques to iterate through the contents of our arraylist. because an arraylist stores items sequentially, we can iterate through an arraylist by looping from its lowest bound through its upper bound, referencing each element by its integral index. the following code snippet is taken from lines 30 through 33 in listing 2.1.1:
for i = 0 to aterritories.count - 1
lblterritories.text = lblterritories.text & _
aterritories(i) & "<br>"
next
the count property returns the number of elements in our arraylist. we start our loop at 0 because all collections are indexed starting at 0. we can reference an arraylist element with: aarraylistinstance(index), as we do on line 32 in listing 2.1.1.
we can also step through the elements of any of the collection types we'll be looking at in this chapter using a for each ... next loop with vb.net (or a foreach loop with c#). a simple example of this approach can be seen in the following code snippet from lines 48 through 52:
dim s as string
for each s in aterritories
lblfewerterritories.text = lblfewerterritories.text & _
s & "<br>"
next
this method is useful for stepping through all the elements in a collection. in the future section "similarities among the collection types," we'll examine a third way to step through each element of a collection: using an enumerator.
if we wanted to grab a specific element from an arraylist, it would make sense to reference it in the aarraylistinstance(index) format. if, however, you are looking for a particular element in the arraylist, you can use the indexof method to quickly find its index. for example,
dim ipos as integer
ipos = aterritories.indexof("illinois")
would set ipos to the location of illinois in the arraylist aterritories. (if illinois did not exist in aterritories, ipos would be set to -1.) two other forms of indexof can be used to specify a range for which to search for an element in the arraylist. for more information on those methods, refer to the .net framework sdk documentation.
working with the hashtable class
the type of collection most developers are used to working with is the hash table collection. whereas the arraylist indexes each element numerically, a hash table indexes each element by an alphanumeric key. the collection data type in visual basic is a hash table; the scripting.dictionary object, used commonly in classic asp pages, is a simple hash table. the .net framework provides developers with a powerful hash table class, hashtable.
when working with the hashtable class, keep in mind that the ordering of elements in the collection are irrespective of the order in which they are entered. the hashtable class employs its own hashing algorithm to efficiently order the key/value pairs in the collection. if it is essential that a collection's elements be ordered alphabetically by the value of their keys, use the sortedlist class, which is discussed in the next section, "working with the sortedlist class."
adding, removing, and indexing elements in a hashtable
with the arraylist class, there were a number of ways to add various elements to various positions in the arraylist. with the hashtable class, there aren't nearly as many options because there is no sequential ordering of elements. to add new elements to a hashtable use the add method.
not surprisingly, there are also fewer methods to remove elements from a hashtable. the remove method dissects a single element, whereas the clear method removes all elements from a hashtable. examples of both of these methods can be seen in listing 2.1.2. the output is shown in figure 2.2.
listing 2.1.2 for sequentially accessed collections, use the arraylist
1: <script language="vb" runat="server">
2:
3: sub page_load(sender as object, e as eventargs)
4: ' create a hashtable
5: dim htsalaries as new hashtable()
6:
7: ' use the add method to add employee salary information
8: htsalaries.add("bob", 40000)
9: htsalaries.add("john", 65000)
10: htsalaries.add("dilbert", 25000)
11: htsalaries.add("scott", 85000)
12: htsalaries.add("billg", 90000000)
13:
14: ' now, display a list of employees and their salaries
15: lblsalary.text = "<i>there are " & htsalaries.count & _
16: " employees...</i><br>"
17:
18: dim s as string
19: for each s in htsalaries.keys
20: lblsalary.text &= s & " - " & htsalaries(s) & "<br>"
21: next
22:
23: ' is billg an employee? if so, fire him!
24: if htsalaries.containskey("billg") then
25: htsalaries.remove("billg")
26: end if
27:
28:
29: ' list the remaining employees (using databinding)
30: dgemployees.datasource = htsalaries.keys
31: dgemployees.databind()
32:
33:
34: htsalaries.clear() ' remove all entries in hash table...
35: end sub
36:
37: </script>
38:
39: <html>
40: <body>
41: <b>employee salary information:</b><br>
42: <asp:label id="lblsalary" runat="server" />
43: <p>
44:
45: <b>remaining employees after round one of firings:</b><br>
46: <asp:datagrid runat="server" id="dgemployees"
47: autogeneratecolumns="true" showheader="false"
48: cellspacing="1" cellpadding="4" />
49: </body>
50: </html>
国内最大的酷站演示中心!