1

Hi I want to override constructor in custom class MyList.

Code below can be compiled, I receive "same erasure" error. For compiler List<CustomClass1> is same type as List<CustomClass2>

Can someone suggest me how to solve this. I try using List<Object> and using instanceof but I can't solve this but without success

private static class MyList {

    private int type;

    public MyList (List<CustomClass1> custom1) {
                 type = 1;
    }

    public MyList (List<CustomClass2> custom2) {
                 type = 2;

    }
}
Brian
  • 5,069
  • 7
  • 37
  • 47
Jovan
  • 4,684
  • 13
  • 64
  • 98
  • possible duplicate of [Method has the same erasure as another method in type](http://stackoverflow.com/questions/1998544/method-has-the-same-erasure-as-another-method-in-type) – Matthew Farwell Nov 07 '11 at 21:05

2 Answers2

1

Because of what is called type erasure the generic type information is lost during compilation. Both compile down to public MyList(List l) when the type information is erased. This is just how Java works. Generics are only available during compile time.

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

1

The java compiler "erases" the type parameter. So List<CustomClass1> and List<CustomClass2> becomes List after the type erasure (de facto the same signature):

public MyList (List list) {
    // ...
}

You could add the type as parameter:

public MyList (List<?> list, int type) {
    // ...
}

or maybe

public MyList (List<?> list, Class<?> clazz) {
    // ...
}

or add type parameter to class

class MyList<T> {

    public MyList (List<T> custom2, Class<T> clazz) {
        // ...
    }
}
jeha
  • 10,562
  • 5
  • 50
  • 69
  • tnx for your answer, but how can I check list type(`CustomClass1` or `CustomClass2`)? I try using ` if (list.getClass().equals(CustomClass1.class)) {` but this not work – Jovan Nov 07 '11 at 21:35
  • @Jovan: if you pass the `Class` as parameter you could add a method `getClazz()` that returns this value and use `list.getClazz().equals(CustomClass1.class)` almost as usual – jeha Nov 07 '11 at 22:00
  • @Jovan: maybe interesting http://stackoverflow.com/questions/6624113/get-type-name-for-generic-parameter-of-generic-class – jeha Nov 07 '11 at 22:19