Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jun 25, 2001

List That Requires Items of the Same Class


The benefits here are that the class can be set at runtime. You don't need to write a new list for every Class that needs listing.
 
public class HomogenousList extends ArrayList
{
   private ArrayList data = new ArrayList();
   private Class itemType;
   public HomogenousList(Class type) {
     itemType = type;
     }

   public void add(Object item) throws IllegalArgumentException
   {
      if (itemType.isInstance(item))
        data.add(item)
	else
        throw new IllegalArgumentException("MESSAGE");
   }

  /**
   * Downside is that caller needs to cast result from Object to 
whatever
   */
   public Object get(int index)
   {
      return arl.get(index);
   }

  /**
   *  Use this to obtain class for casting after call to get()
   */
   public Class getType() {
     return itemType;
     }
}

Users should wrap all List methods that they want to use (getAll, addAll, etc.). This is more work up front, but the class only needs to be written once. Heck, email me for GNU GPL'd implementations of the full bit! Rod G at:
Rod Gammon
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap