Java Generics continue
I don’t have so much time to continue writing interesting points about java generics. So I am summarizing some advanced portion of java generics here with enough practical explanation excluding tedious theory.
If you are missing something or something is unclear or you really need some good examples then drop your comments. I’ll update this article as per your desire. But first go through my first article: Java Generics – Boys are not allowed in Girls community
Review the below code
//--Wrong--
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // compile time error
}}
let me explain the reason.
- fromArrayToCollection() says that elements of Object[] a can be added to Collection c.
- An Object array can have array of String or Number or any other class since it is the parent class of any class.
- Collection< ? > c can be of ? type ie String or Number etc
It means, below statements must be acceptable
Number[] na = new Number[100]; Collection<String> cs = new ArrayList<String>(); fromArrayToCollection(na, cs);// compile-time error
A Number can not be added to a Collection of String. Correct syntax would be as below;
//--Right--
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // correct
}}
Had we discussed A,B,...E...T...Z before? .... OOPs I forgot to tell you. Actually,
This area is protected to registered users only.
86
views
views


No Comments