0

I'm developing a Java library and I need to create a method which returns a Set<A>, where A is an interface and B implements A. So I tried instantiating the set like:

Set<A> setOfA = new HashSet<B>();

getting the following error:

Type mismatch: cannot convert from HashSet<B> to Set<A>

However, when not using a collection and returning B in a function which expects A as return type everything is ok, so the relation between the interface and its concrete class is ok and the problem is with collections, the HashSet in this case. How can I avoid this? Thanks in advance.

RVKS
  • 147
  • 3
  • 16

1 Answers1

1

You can do it like this only:

Set<A> setOfA = new HashSet<>();

It's a short way of this:

Set<A> setOfA = new HashSet<A>();

So whan you need to use special methods from B, just do cast like this (if you are sure, that this object is really instance of B)

B b = (B) setofA.get(....);

You can read pretty good tutorial here. Good luck

mchern1kov
  • 450
  • 3
  • 10