Why can't I define these two constructors in Java for the same 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 Set, the code compiles. Why?

+4
source share
3 answers

If you

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

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

Erasing a type turns them into:

MyClass(Set setOfA) { ... }

MyClass(Set setOfB) { ... }

So now they are the same, and the compiler is confused.

However, if one of them was HashSet, you get the following:

MyClass(Set setOfA) { ... }

MyClass(HashSet setOfB) { ... }

And now they are different enough for the compiler to determine what to bind to at compile time.

+7
source

- , Java ( Java):

  • Object, ...
  • , .
  • .

, Java :

MyClass(Set setOfA) { ... }

MyClass(Set setOfB) { ... }

. .

+5

, . , , , - MyClass(Set<A>) MyClass(Set<B>) MyClass(Set).

Oracle : http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

+3
source

Source: https://habr.com/ru/post/1541004/


All Articles