Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
Emil Avatar asked Dec 06 '22 02:12

Emil


1 Answers

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.

like image 101
awksp Avatar answered Dec 28 '22 08:12

awksp