In-Class Exercise Collections: ArrayList Exercise

advertisement
In-Class Exercise
Collections: ArrayList Exercise
In groups, write a small program section that manipulates an ArrayList of String and
decimal objects.
The following reference can help you do the exercise:
ArrayList name = new ArrayList();
name [i]
x is Decimal
x is String
//creates a new ArrayList
//retrieves or sets a member of an ArrayList
//true if x is a Decimal, otherwise false
//true if x is a String, otherwise false
ArrayList methods and properties:
void Insert(index, object) //Inserts the specified object
void Remove (object)
//Removes the specified object
void Add (object)
//Adds an object to the end of the ArrayList
void RemoveAt (index)
//Removes the object at the specified index
Count
//Property containing the current length of the Arraylist
Additional concept:
If you are not sure of the class of an object when retrieving it from an ArrayList, you can test
using the is comparison operator. This is not in the book but you may need it elsewhere in
this class. For example:
If (v2[i] is Decimal) then
{
listBox1.Items.Add(((Decimal)v2[i]).ToString());
}
else {
listBox1.Items.Add(((String)v2[i]).ToString());
}
Construct the program to do the following:
1) Create an ArrayList called names.
2) Set the first position in your ArrayList to the name (a String) of the first person
in your group. Set the second position in your ArrayList to a made-up id number
(a decimal) of the first person in your group. Do this for the remaining people in your
group so that the ArrayList looks like this:
Name1
String
21.3
decimal
Name2
String
33.2
decimal
Name3
String
42.1
decimal
Delete the name and id of the first person in the ArrayList.
Insert a new name and id in the second position of the ArrayList.
Add a new person’s name and id after the last position of the ArrayList
Write a look that adds a new line to a listbox called listBox1 displaying each item
in the ArrayList.
(Continued)
3)
4)
5)
6)
The program should determine whether or not the object in each position is a String or
a Decimal. In other words, it should not be hard-coded to simply alternate between
displaying the String at position n and the Decimal at position n.
Download