Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my java class implement methods I don't expect?

I have this interface:

public interface IDeck<T extends IDeck<T,S>,S extends ICard<S>> extends Comparable<T>, Collection<S>{
    public Set<S> getDeck();
    public void setDeck(Set<S> newDeck);
}

And I then make a class implement it, here is the header and the first few methods:

public class PlayingCardDeck implements IDeck<PlayingCardDeck,PlayingCard> {

    @Override
    public int compareTo(PlayingCardDeck o) {
        // TODO Auto-generated method stub
        return 0;
    }

Good so far, I want it to be comparable.

    @Override
    public boolean add(PlayingCard e) {
        // TODO Auto-generated method stub
        return false;
    }

Yup, it can contain PlayingCards

    @Override
    public boolean addAll(Collection<? extends PlayingCard> c) {
        // TODO Auto-generated method stub
        return false;
    }

This is Ok I think, so long as the collection element extends PlayingCard, though this doesn't match the add(PlayingCard e) method.

    @Override
    public boolean contains(Object o) {
        // TODO Auto-generated method stub
        return false;
    }

Hang on? Why is the type here Object and not PlayingCard ?

public Object[] toArray() {
    // TODO Auto-generated method stub
    return null;
}

So any array has to be of Objects, not PlayingCards?

Why am I getting 'weird' functions implemented from my interface, and not the generics I supplied? What have I missed?

like image 533
AncientSwordRage Avatar asked Feb 01 '26 21:02

AncientSwordRage


1 Answers

Because Collection.contains(Object) has Object as its parameter. It's not defined as Collection.contains(E). As for why that is, you can find a detailed explanation here.

like image 103
Daniel Kaplan Avatar answered Feb 03 '26 11:02

Daniel Kaplan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!