users
[Top] [All Lists]

An Idea for Generics in JDK1.4

To: "'users@xxxxxxxxxx'" <users@xxxxxxxxxx>
Subject: An Idea for Generics in JDK1.4
From: Amol Deshmukh <adeshmukh@xxxxxxxxxxxxxx>
Date: Wed, 30 Mar 2005 09:53:36 -0500
Delivered-to: mailing list users@cinjug.org
Mailing-list: contact users-help@cinjug.org; run by ezmlm
When dealing with APIs that return Collection of /SomeClass/
instances, you need to dig into the source code to figure out what
to cast the retrieved value to (unless the API doc explains it :)

Creating custom collections by delegation to standard collections
seems to be a simple solution to this problem. 

To illustrate with code:

/* 
 * Lets say I return a List of MyThing objects, I could write a
 * CustomList that is backed by a std List as: 
 */

<code>
public class MyThingList {
  public MyThing get(int index) {
    (MyThing) internalList.get(index);
  }
  public void add(MyThing thing) {
    internalList.add(thing);
  }
  public MyThingIterator iterator() {
    return new MyThingIterator(internalList.iterator());
  }
  // do the other List methods, you get the idea

  /* 
   * CustomIterator that delegates to std iterator
   */
  public static class MyThingIterator {
    public MyThingIterator(Iterator iter) {
      internalIterator = iter;
    }
    public MyThing next() {
      return (MyThing) internalIterator.next();
    }
    // do the other iterator methods, you get the idea
  }
}
</code>

The disadvantages:
- Will have to write a class for every Map/Set/List/Collection
that we use. 
- Cannot switch Map/List.. implementations easily (Like use
HashSet instead of TreeSet as the underlying collection)

The advantages are:
- Self Explanatory API (to some extent)
- No need of casting in code that uses the API: Better static checking
- Could be made into an eclipse plugin (atleast in theory)
  ... which counters the first disadvantage to an extent.


I would imagine that this is similar to what the Generics 
should be doing behind the scenes, with the advantage ofcourse
that you dont have to write the custom collection class - the
compiler generates it for you.

Still, in "JDK < 1.5" simulating generics seems to be worthwhile
(heck, we could even have an eclipse plugin that generates 
the simulator class)

I dont imagine I am the first to come across the problem or
this solution - AND - I have never used this approach myself :)
So i would like to have comments or criticism of this approach
from others:
  - is this a fairly common solution?
  - are there some known problems with this approach?
  - the disadvantages outweigh the advantages because....
etc.

~ amol

<Prev in Thread] Current Thread [Next in Thread>