Storing different types of elements in a List in Java

Since the common ancestor of your classes is Object, and because List<? extends Object> does not make things any cleaner (after all, everything extends Object) it looks like List<Object> would be an OK choice.

However, such list would be a mixed bag: you would need to check run-time type of the object inside, and make decisions based on that. This is definitely not a good thing.

A better alternative would be creating your own class that implements operations on elements of the list the uniform way, and make one subclass for each subtype that implements these operations differently. This would let you treat the list in a uniform way, pushing the per-object differentiation into your wrappers.

public interface ItemWrapper {
    int calculateSomething();
}

public abstract class IntWrapper implements ItemWrapper {
    private int value;

    public IntWrapper(int v) {
      value=v; 
    }

    public int calculateSomething() {
      return value;
    }
}

public abstract class DoubleListWrapper implements ItemWrapper {
    private List<Double> list;

    public DoubleListWrapper (List<Double> lst) {
      list = lst; 
    }

    public int calculateSomething() {
        int res;
        for (Double d : list) {
            res += d;
        }

        return res;
    }
}
// ...and so on

Now you can make a list of ItemWrapper objects, and calculateSomething on them without checking their type:

List<ItemWrapper> myList = new ArrayList<ItemWrapper>();

for (ItemWrapper w : myList) {
    System.out.println(
      w.calculateSomething());
}

Leave a Comment