12.1. What are Generics?
The best way to appreciate what generics bring to the programming table is with an example. Sorting data is a very common programming problem. I once was interviewed for a consulting job and part of the interview was a programming test in which I was expected to generate a series of random numbers, display them in a listbox, sort them into ascending order, and redisplay them in a second listbox. The interviewers weren't happy when I bypassed writing my own sort routine and simply turned on the Sorted property in the second listbox. Moral: know your toolkit. But suppose you have to sort a series of integer data into ascending order and you can't use the listbox trick. How would you write the solution?
Try It Out: QuicksortWhile volumes have been written on sorting algorithms, one of the fastest general-purpose sorts is the Quicksort. The algorithm uses a divide-and-conquer approach to partitioning the data and then calls itself recursively to perform the sorting task. A sample run of the program is shown in Figure 12-1. Figure 12-1. Figure 12-1
The listbox object on the left shows the "raw" data produced by the generation of 10 integer values using the pseudo-random number class (Random). After the user clicks the Sort button, that same list of numbers is sorted and then displayed in the second listbox object. (No, I didn't take the shortcut and simply ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access