
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Replacing the Stack and Queue with Their Generic Counterparts
|
233
Discussion
On the surface, the generic and nongeneric Queue and Stack classes seem similar
enough. However, it is a very different story underneath the surface. The basic use of
the generic
Queue and Stack objects are the same as with their nongeneric counter-
parts, except for the syntax used to instantiate the objects. The generic form requires
a type argument in order to create the type. The type argument in this example is an
int. This type argument indicates that this Queue or Stack object will be able to con-
tain only integer types, as well as any type that implicitly converts to an integer, such
as a
short:
short s = 300;
numericQueue.Enqueue(s); // OK, because of the implicit cast
However, a type that cannot be implicitly converted to an integer, such as a double,
will cause a compile-time error.
double d = 300;
numericQueue.Enqueue(d); // Error, no implicit case available
numericQueue.Enqueue((int)d); // OK, because of the explicit cast
The nongeneric form does not require this type argument, because the nongeneric
Queue and Stack objects are allowed to contain only elements of type Object.
When choosing between a generic and nongeneric
Queue or Stack, you need to decide
whether or not you wish to use a strongly typed ...