dcsimg
Collection classes in Java aren't template classes - a workaround (part 2)
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Jon_Thorarinsson
Posted On:   Monday, March 4, 2002 05:58 AM

Here's an additional info to the previous discussion. I've found a way to make (99%) type-safe template collection classes in Java . It's 99% percent type safe in the sense that insertions of the wrong type will cause a ClassCastException to be thrown, extractions from the collection classes will be the same as before (you have to make a runtime cast to the correct type), and only the default constructor of the Collection classes (ArrayList, HashMap, etc.) can be used without minimal hassle. The benefits offered by this are: Type-safe insertions. The program detects an incorrect insertion at the time of the insertion and not the extraction. The name of the template collection classes give a   More>>

Here's an additional info to the previous discussion. I've found a way to make (99%) type-safe template collection classes in Java . It's 99% percent type safe in the sense that insertions of the wrong type will cause a ClassCastException to be thrown, extractions from the collection classes will be the same as before (you have to make a runtime cast to the correct type), and only the default constructor of the Collection classes (ArrayList, HashMap, etc.) can be used without minimal hassle.


The benefits offered by this are:


  • Type-safe insertions. The program detects an incorrect insertion at the time of the insertion and not the extraction.
  • The name of the template collection classes give an indication of the element type: By subclassing the Java collection classes and interfaces with an empty class body and a descriptive name, the types of the collection elements are always clear. You will no longer see something like private List mUserIDs, which is confusing because a userID could be a string but it could also be a structure with more info. This is not clear from such a definition. My type-safe template collection classes attempt to remedy this as much as possible.


Criticism will be well accepted. I have no idea if there already exists an alternative solution of the Collection class problem.


Here's an example of a type-safe template ArrayList and an example of its usage in the form of a List of String objects (the interface String_List ):



- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
package com.oz.johnny.utils;


import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

import java.util.List;


// An example of a "type-safe template" list:

// List of String objects. The type-safe-insertion version.

// use: String_List list = new String_ArrayList();

interface String_List extends List{}

class String_ArrayList extends TArrayList implements String_List

{

    String_ArrayList()

    {

          super (String.class);

    }

}


// A type safe ArrayList

public class TArrayList extends ArrayList

{

     private Class mClass; // This is what makes the class "type-safe".


     private boolean collectionContainsWrongTypes(Collection c)

    {

          for (Iterator it = c.iterator(); it.hasNext();)

         {

               if (!mClass.isInstance(it.next()))

              {

                    return true ;

              }

         }


          return false ;

    }


     public TArrayList(Class elementTemplate)

    {

         mClass = elementTemplate;

    }


     public boolean add(Object o)

    {

          if (!mClass.isInstance(o))

         {

               throw new ClassCastException();

         }


          return super .add(o);

    }


     public boolean addAll(Collection c)

    {

          if (collectionContainsWrongTypes(c))

         {

               throw new ClassCastException();

         }


          return super .addAll(c);

    }


     public boolean addAll(int index, Collection c)

    {

          if (collectionContainsWrongTypes(c))

         {

               throw new ClassCastException();

         }


          return super .addAll(index, c);

    }


     public Object set( int index, Object element)

    {

          if (!mClass.isInstance(element))

         {

               throw new ClassCastException();

         }


          return super .set(index, element);

    }


     public void add( int index, Object element)

    {

          if (!mClass.isInstance(element))

         {

               throw new ClassCastException();

         }


          super .add(index, element);

    }


    // A simple test of the class

     public static void main(String[] args)

    {

         // See definition of String_List and String_ArrayList

         // at the bottom of the file

         String_List list = new String_ArrayList();


          try

         {

              list.add( new String("hi")); // correct type

              list.add( new Integer(0));    // should throw, because an

                                                  // incorrect type is being

                                                  // inserted

         }

          catch (ClassCastException e)

         {

               System.out.println("good");

         }


          if (((String)list.get(0)).equals("hi"))

         {

              System.out.println("good");

         }

          else

         {

              System.out.println("bad");

         }


         foo(list);

    }


    // An example of passing a String_List as a

    // parameter to a method. It's obvious from

    // the typename of the parameter that this

    // is a list of String objects

     private static void foo(String_List list)

    {

         // Create a Collection and insert one String object

         // and one Integer object

         Collection c = new ArrayList();

         c.add( new String("yes"));

         c.add( new Integer(0));


          try

         {

              list.addAll(c); // should throw, because an

                                // incorrect type is being inserted

                                // (the second item in 'c')

         }

          catch (ClassCastException e)

         {

              System.out.println("good");

         }

    }

}

   <<Less

Re: Collection classes in Java aren't template classes - a workaround (part 2)

Posted By:   Duncan_Forster  
Posted On:   Monday, March 4, 2002 06:37 AM

Yes, there already is an alternative solution. Check out JSR-014.
It uses the same format as C++ (ie Vector x = new Vector()). It is basically a modified compiler that produces standard bytecode that is backward compatiable. Chech it out.
About | Sitemap | Contact