devxlogo

List That Requires Items of the Same Class

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 writtenonce. Heck, email me for GNU GPL’d implementations of the full bit! Rod G at:

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist