336
LESSON 28 Making generic classes
Lesson Requirements
Start a new project and give it an
ArrayMethods class.
Create a generic
Randomize method with one generic type parameter T. The method should
take as a parameter an array of
T and return an array of T.
Make the main program test the method.
Hints
Use the following code for the method’s body. Try to figure out the method’s declaration
yourself before you read the step-by-step instructions that follow.
// Make a Random object to use to pick random items.
Random rand = new Random();
// Make a copy of the array so we don’t mess up the original.
T[] randomizedItems = (T[])items.Clone();
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
// Pick a random item j between i and the last item.
int j = rand.Next(i, items.Length);
// Swap item j into position i.
T temp = randomizedItems[i];
randomizedItems[i] = randomizedItems[j];
randomizedItems[j] = temp;
}
// Return the randomized array.
return randomizedItems;
Step-by-Step
Start a new project and give it an
ArrayMethods class.
1. This is reasonably straightforward. You don’t need to make the ArrayMethods class
generic.
Create a generic
Randomize method with one generic type parameter T. The method should
take as a parameter an array of
T and return an array of T.
1. The following code shows how you can implement this method:
// Randomize the items in an array.
public static T[] Randomize<T>(T[] items)
{
596906c28.indd 336 4/7/10 12:34:14 PM
Try It
337
// Make a Random object to use to pick random items.
Random rand = new Random();
// Make a copy of the array so we don’t mess up the original.
T[] randomizedItems = (T[])items.Clone();
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
// Pick a random item j between i and the last item.
int j = rand.Next(i, items.Length);
// Swap item j into position i.
T temp = randomizedItems[i];
randomizedItems[i] = randomizedItems[j];
randomizedItems[j] = temp;
}
// Return the randomized array.
return randomizedItems;
}
Make the main program test the method.
1. The program I wrote uses two TextBoxes, one to hold the original items and one to
display the randomized items. When you click the Randomize button, the following
code executes:
// Randomize the list and display the results.
private void randomizeButton_Click(object sender, EventArgs e)
{
// Get the items as an array of strings.
string[] items = itemsTextBox.Lines;
// Randomize the array.
string[] randomizedItems = ArrayMethods.Randomize<string>(items);
// Concatenate and display the result.
randomizedTextBox.Text = string.Join(“ ”, randomizedItems);
}
Notice that the code uses the TextBox’s Lines property to get the entered values. That
property returns the lines in a multiline
TextBox as an array of strings.
Also notice that the code doesn’t need to make an instance of the
ArrayMethods class.
That’s the advantage of making the
Randomize method static.
Please select Lesson 28 on the DVD to view the video that accompanies this lesson.
596906c28.indd 337 4/7/10 12:34:14 PM
338
LESSON 28 Making generic classes
EXERCISES
1. Finish building the generic Alternate method described earlier in this lesson. Add the code
needed to make the alternating version of the list. To make using the method easy, make it
static in the
ArrayMethods class. Make the main program test the method with lists containing
odd and even numbers of items.
2. Make the TreeNode class to represent a tree node associated with a piece of data of some
generic type. In addition to the code shown earlier in this lesson, give the class:
An
AddChild method that adds a new child node to the node for which the method
is invoked. Have the method take a piece of data of the class’s generic type as a
parameter and return a new
TreeNode representing that piece of data.
A private
AddToListPreorder method that adds a node’s subtree to a list in pre-
order format. The preorder format lists the node’s data first and then recursively
calls the method to add the data for the node’s children. You can use code similar
to the following:
// Recursively add our subtree to an existing list in preorder.
private void AddToListPreorder(List<TreeNode<T>> list)
{
// Add this node.
list.Add(this);
// Add the children.
foreach (TreeNode<T> child in Children)
{
child.AddToListPreorder(list);
}
}
A public
Preorder method that returns the node’s subtree items in a list in preorder
format. The method should call
AddToListPreorder to do all of the work. You can
use code similar to the following:
// Return a list containing our subtree in preorder.
public List<TreeNode<T>> Preorder()
{
List<TreeNode<T>> list = new List<TreeNode<T>>();
AddToListPreorder(list);
return list;
}
For extra credit, add similar methods to build lists in postorder and inorder. In
postorder, a node recursively adds its children to the list and then adds its own data.
In inorder, a node recursively adds the first half of its children to the list, then itself,
and then the rest of its children.
Make the main program build the tree shown in Figure 28-1, although it doesnt need to dis-
play it graphically as in the figure. Make the program display the tree’s preorder, postorder,
and inorder representations as shown in Figure 28-2.
596906c28.indd 338 4/7/10 12:34:14 PM
Exercises
339
A
B
E
IG
H
FDC
FIGURE 281
FIGURE 282
3. Make a generic PriorityQueue class. The class is basically a list holding generic items where
each item has an associated priority. Give the class a nested
ItemData structure similar to
the following to hold an item. This structure is defined inside the
PriorityQueue class and
won’t be used outside of the class, so it can be
private. Note that this structure uses the
class’s generic type parameter
T for the data it holds.
// A structure to hold items.
private struct ItemData
{
public int itemPriority { get; set; }
public T data { get; set; }
}
The class should store its ItemData objects in a generic List.
Give the
PriorityQueue class a public Count property that returns the number of items in
the list.
Give the class an
AddItem method that takes as parameters a piece of data and a priority. It
should make a new
ItemData to hold these values and add it to the list.
Finally, give the class a
GetItem method that searches the list the item with the smallest pri-
ority number (priority 1 means top priority), removes that item from the list, and returns the
item and its priority via parameters passed by reference. (If there’s a tie for lowest priority
number, return the first item you find with that priority.) (Hint: Should you use
ref or out
to pass the parameters by reference?)
You can download the solutions to these exercises from the book’s web page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find those
solutions in the Lesson28 folder.
596906c28.indd 339 4/7/10 12:34:16 PM
Click here to Play
596906c28.indd 340 4/7/10 12:34:16 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.221.133