Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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))
        throw new IllegalArgumentException("MESSAGE");

   * Downside is that caller needs to cast result from Object to 
   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.



Thanks for your registration, follow us on our social networks to keep up-to-date