Robbo_UK
Robbo_UK

Reputation: 12149

Generics Set with Enums

Problem space has been stripped down.

So I have the following interface that I cannot change.

public interface ItemInterface {
  Set<Enum<?>> getItems();
}

I have created the Items enum class

public enum Item{
  ITEM1, ITEM2, ITEM3 
}

So when I implement the method It does not compile.

public class ItemImpl implements ItemInterface {

    @Override
    public Set<Enum<?>> getItems() {
        Set<Item> vals = new HashSet<>();
        vals.add(Item.ITEM1);
        return vals;  
    }
}

The return type does not match and I get compile errors? Any ideas?

Upvotes: 0

Views: 70

Answers (2)

How about this, I have changed the interface, coz simply its makes a bit readable. If your interface is part of any other package, @Lino answer can be used

public interface ItemInterface {

    Set<? extends Enum> getItems();
}



public enum Item implements ItemInterface{
    ITEM1, ITEM2, ITEM3;

    @Override
    public Set<? extends Enum> getItems() {
        Set<Item> as = new HashSet<>();
        as.add(ITEM3);
        return as;
    }
}

Upvotes: 0

Lino
Lino

Reputation: 19926

Simply declare the vals as Set<Enum<?>>:

public class ItemImpl implements ItemInterface {

    @Override
    public Set<Enum<?>> getItems() {
        Set<Enum<?>> vals = new HashSet<>();
        vals.add(Item.ITEM1);
        return vals;  
    }
}

Upvotes: 4

Related Questions