Generics are a great addition to any programming language and it's the sort of feature that reduces a lot of coding and unnecessary type castings.
For example a lot of constructs in object oriented programming languages use the object type when the data type a programmer will use is not known. If i am defining my own version of a queue as a library, i will not know the data type of the objects the end user of my queue will store. So when adding and retrieving elements i'll be resorted to using the object type since it can store any type of objects. The real problem here is typically the user of my queue will already know what type of objects he is going to store. But still since i am using the object type each time an element is retrieved it has to be type casted into the proper data type. This is very time consuming and a real pain. And if an invalid type is added to the queue a run time exception will be thrown...
So what is the solution? Ideally when i define the queue i should be able to use a placeholder for the type without specifying a concrete type. The user of my queue should be able to replace the placeholder with a specific type when creating an instance of my queue. So since the specific data type the queue is going to use is defined, the compiler can take care of not allowing objects of other data types to be added. This is exactly what generics are.I'll post a few samples on this for the new VS.NET 2005(alias Whidbey) as well as the new Java 5.0(alias Tiger) in my upcoming blogs...
No comments:
Post a Comment