Curious
Curious

Reputation: 921

generics type parameter hiding the type

I created the interface Card as follows

  public interface Card extends Comparable<Card> {
    .....
    }

then 

    public interface Deck<Card> {
          public void add(Card card);
    }

In Deck interface with type parameter I'm getting the warning type parameter is hiding the type Card. I can as well declare the type T instead of Card but it makes more sense that the Deck to hold the Card Objects not more than that.

I read some old posts but not getting the clear sense of why the warning and what exactly the practical significance / why the compiler is complaining.

Upvotes: 0

Views: 890

Answers (2)

Pulkit Gupta
Pulkit Gupta

Reputation: 1059

Generics mean that you want a class which can work with different datatypes based on the specific type you want for a particular instance. For example consider these lists : the first list can hold integers and the second list can hold string and can provide all the operations irrespective of the datatype used in a particular instance.

List<Integer> list1 = new ArrayList<>(); List<String> list1 = new ArrayList<>();

In case you do not want the deck to store any thing other than Card then it does not justify the use for generics.

For the second part so to why compiler is showing a warning is because the Deck interface is just considering <Card> as a place holder and not the Card interface. Thus to explicitly tell you this the compiler is showing this warning.

Upvotes: 0

rosstex
rosstex

Reputation: 825

Deck<Card>

specifies the word "Card" as a placeholder for a type within the Deck class, the same way that

Deck<T>

does: it's just a placeholder.

If you never intend a deck to hold anything other than cards, your best option is to get rid of the generic type in Deck all together.

Upvotes: 3

Related Questions