The advantage of using generics is that it increases the type safety - you can only put in the correct type of thing, and you get out the correct type without requiring a cast. The only reason I can think of for not using generic collections is that you need to store some arbitrary data. Am I missing something? What other reasons are there to not use generics when dealing with collections?
The following are the non-generic collections: ArrayList, BitArray. ArrayList − It represents ordered collection of an object that can be indexed individually. ArrayList is an alternative to an array.
Code reusability: Generics help in reusing the code already written, thereby making it usable for other types (for a method, or class, or an interface).
Generic classes are used to provide the type safe structure -- type safe means only one type of data can be contained within Generic classes. The data type is defined at the time of an object initialization. We can have a different type of collection.
The generic collections are introduced in Java 5 Version. The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes.
If you need to store arbitrary data, use List<object>
(or whatever). Then it's absolutely clear that it's deliberately arbitrary.
Other than that, I wouldn't use the non-generic collections for anything. I have used IEnumerable
and IList
when I've been converting an object
reference and didn't know the type to cast it to at compile-time - so non-generic interfaces are useful sometimes... but not the non-generic classes themselves.
The obvious other reason is working with code (possibly legacy) that does not use generic collections.
You can see this happening in .NET itself. System.Windows.Form.Control.Controls
is not generic, nor is System.Web.UI.Control.Controls
.
Generics are almost always the right thing to use. Note that languages like Haskell and ML essentially only allow that model: there is no default "object" or "void*" in those languages at all.
The only reasons I might not use generics are:
When the appropriate type is simply not known at compile time. Things like deserializing objects, or instantiating objects through reflection.
When the users that will be using my code aren't familiar with them (yet). Not all engineers are comfortable using them, especially in some more advanced patterns like the CRTP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With