Java: Wildcard type vs plain type

Viewed 66

A method eat() uses a parameter of type Food, while Food is a generic class:

class Food<T> {
    T type; 
    ...
}


class Human {
    public void eat Food(Food food) {
        // eat, eat, and eat, however it has nothing to do with T
    }
}

The question is, should I declare Food<?> instead of Food in eat's parameter? Are there any difference while the method eat doesn't care and use anything related with T?

1 Answers

If you use just Food, then you're using a raw type. The compiler will issue a warning, since it loses any information and cannot do any type checks on subsequent uses of this type. So if you don't care about T inside the method, use Food<?> and let the compiler know about this fact.

Related