I have a question about using generics with collections.
ArrayList<Integer> al=new ArrayList<Integer>();
We know that the above line means that ArrayList
al
is restricted to hold only integers. So the following line gives a compilation error:
al.add("wwww");
But I don't understand what the below line means,
ArrayList al=new ArrayList<Integer>();
Where we don't give ArrayList<Integer>
at the left side while declaring. Now the following line doesn't give a compilation error:
al.add("wwww");
So if I declare like
ArrayList al=new ArrayList<Integer>();
that means a1
can accept any types?
What's the difference between those two declarations?
Generic collection types also generally perform better than the corresponding nongeneric collection types (and better than types that are derived from nongeneric base collection types) when the collection elements are value types, because with generics there is no need to box the elements.
These generic collections allow the datatypes to pass as parameters to classes. The Compiler is responsible for checking the compatibility of the types. Generics allows a single type of object.
The .NET class library provides a number of generic collection classes in the System.Collections.Generic and System.Collections.ObjectModel namespaces. For more detailed information about these classes, see Commonly Used Collection Types. Many of the generic collection types are direct analogs of nongeneric types.
The dot net framework has re-implemented all the existing collection classes such as ArrayList, Hashtable, Stack, and Queue, etc. in Generic Collections such as ArrayList<T>, Dictionary<TKey, TValue>, Stack<T> and Queue<T>. Here T is nothing but the type of values that we want to store in the collection.
The latter declaration (without generic type) is obsolete and deprecated. You shouldn't use it, it compiles only for backward compatibility. Modern IDEs will generate warning here.
Also note that Java only enforces generic types at compile time, so technically you can add incorrect type to a collection with some extra casts. That's why it is better to stay with generics all the time and do not bypass them.
With this code:
ArrayList al = new ArrayList<Integer>();
a1.add("www");
the compiler will generate a warning (which you should heed!) but the code will run without error. The problem comes on extracting data from a1
. If you "know" that it contains Integer
values, you can just do this:
Integer val = (Integer) a1.get(index);
But when you hit the "www"
element you're going to get a ClassCastException
. Generics are meant to move such errors to compile time instead of forcing the poor developer to track down how a String
value ended up in that Integer
array list.
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