0

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?

2

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.

  • 2
    Instead of equals, you might want to use isInstance so it'll also accept child types. – Idan Arye Apr 6 '14 at 12:50
  • @IdanArye Do you mean instanceof? – Azar Apr 6 '14 at 13:31
  • Class.isInstance(Object) (its in the comment in posted code fragment) – Maciej Chałapuk Apr 6 '14 at 13:35
  • @Azar Not exactly. instanceof is a keyword and in order to use it you to write the name of the class inside the code. isInstance is a method of Class that you can use when you have the class as class object, and does the same thing as instanceof. – Idan Arye Apr 6 '14 at 13:36
  • @MaciejChałapuk Sorry, didn't notice it. Still - isInstance as been around since Java 1.1 so I doubt it's not available on any Java platform that's still being used. Asker's platform is old, but it can't be that old... – Idan Arye Apr 6 '14 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.