Leo Leo - 6 months ago 20
Java Question

Java assigning Set of Interface

I think this is simple question, but I stuck on it.
I am trying to assign one Set to another:

Set<Registrable> rr =kart.getReg();


where kart.getReg() return Set of Reg:

public class Kart {
public Set<Reg> getReg() {
return reg;
}
...


but "Registrable" is an interface, defined like:

public interface Registrable {
getters...
setters...
}


and finally the class "Reg" is:

public class Reg implements Registrable {
getters...
setters...
}


and my compiler wrote:

Type mismatch: cannot convert from Set<Reg> to Set<Registrable>


Any help will be appreciated!

Answer

Generics let you enforce compile-time type safety on Collections.

So you can't use -

Set<Registrable> rr =kart.getReg();

But you can use wildcard like the following.

Set<? extends Registrable> rr = kart.getReg();

Notice :: you can't modified the Set rr.

For example rr.add(....) will give you compile error.