Java – Generics list without generics

genericsjava

I am using a very primitive Java that doesn't have Generics, and also I can't use reflection.

I want to create a generic list so it would be typed safe (i.e. I only have a list that contains Objects and I want to create a list that contains specific object and not a mix).

On the other hand I also don't want to create a different class for each possible list.

Is there any other way to do that without the use of Generics?

Best Answer

Yes, there is. It will be fully run-time solution (no compile-time type checking), but it's worth it (you will get an early crash on first attempt to insert an object with wrong type).

public class TypedArrayList extends ArrayList {
    private final Class elementType;

    public TypedList(Class elementType) {
        this.elementType = elementType;
    }

    @Override
    public boolean add(Object element) {
        // preffered version, use it if it's available on your platform
        // if (!elementType.isInstance(element)) {
        if (!elementType.equals(element.getClass())) {
             throw new IllegalArgumentException("Object of type " + element.getClass() + "passed to List of "+ elementType);
        }
        return super.add(element);
    }

    // override other methods
    // that need type checking
}

Usage:

TypedArrayList list = new TypedArrayList(String.class);
list.add("works!");
list.add(new Object()); // throws exception

You can do the same for LinkedList and any other list type.