Generics in Java 5.0

October 12th, 2007 | Tags:

Of all the new topics in Java 5.0, the most confusing has been Generics, atleast for me. I realised that, while studying for SCJP 1.5, I would need a summary of generics so it doesn’t escape me a little while later.

This is what I have been able to understand about Generics so far:

1. ? extends Object

        a. What can be added to say, List<? extends Number> a = new ArrayList<Integer>();

            Absolutely nothing except null’s. The list is read only and is used by addAll() etc in the List interface.

        b. What do we get when elements are removed?

            The above returns an object of Number when we execute a.get(0);

 

2. ? super Number

        a. What can be added to say, List<? super Number> a = new ArrayList<Number>();

            Only Number objects and subclasses of Number, not even Object objects are allowed.

        b. What do we get when elements are removed,

            The above returns an Object when we execute a.get(0). Because the return type HAS to be a supertype of Number and Number can effectively have many supertypes, the safest thing to do is to return an Object and leave the rest upto the programmer.

 

Summary :

  • ? extends Whatever means the Collection is read-only and no objects can be added to it. (null is allowed)
  • ? extends Whatever means we get an object of Whatever when we retrieve anything.
  • ? super Whatever means you can only ADD Whatever Objects (and the subtypes of Whatever) to the collection. Nothing else.
  • ? super Whatever means you get Object’s when you get anything from the collection.
Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark

No related posts.

No comments yet.