Search code examples
javaconstructortype-erasure

Why can't I define these two constructors in Java for a single class?


I am defining a constructor for a class, and I have these two definitions:

MyClass(Set<ClassA> setOfA) { ... }

MyClass(Set<ClassB> setOfB) { ... }

I get the following error:

MyClass(java.util.Set<ClassA>) is already defined in MyClass
    MyClass(Set<ClassB> setOfB)

If I specifically made one of them a HashSet instead of a Set, the code compiles. Why?


Solution

  • If you have

    MyClass(Set<A> setOfA) { ... }
    
    MyClass(Set<B> setOfB) { ... }
    

    Type erasure turns them into:

    MyClass(Set setOfA) { ... }
    
    MyClass(Set setOfB) { ... }
    

    So now they're the same, and the compiler is confused.

    However, if one of them were a HashSet, you end up with this:

    MyClass(Set setOfA) { ... }
    
    MyClass(HashSet setOfB) { ... }
    

    And now they're sufficiently different for the compiler to determine which to bind at compile time.