ए भाई Think ज़रा हटके
Note: amtyThumb must be installed for new version of amty thumb post/recent

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.


Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

86
views


To book below area mail me




captcha

You can follow any responses to this entry through the RSS 2.0 feed.