1

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!

Leo
  • 1,029
  • 4
  • 19
  • 40

1 Answers1

2

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 add items to the Set rr.

For example -

rr.add(someItems); //will give you compile error.

If you want to add items to the Set, you can use the following.

Set<? super Reg> rr = kart.getReg();

It can accept Reg and it's supper classes and you can use rr.add(someItems) without compile error.

Necromancer
  • 869
  • 2
  • 9
  • 25