Are there any advantages of using wildcard-type generics in the Bar
class over completely skipping them?
public class Foo<T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
}
Are there any advantages of using wildcard-type generics in the Bar
class over completely skipping them?
public class Foo<T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
}
There are multiple advantages.
They give more type safety. For example, consider if Foo
was List
instead. If you used List
instead of List<?>
, you could do this:
myBar.getFoo("numbers").add("some string");
even if the list was only supposed to contain Number
s. If you returned a List<?>
, then you would not be able to add anything to it (except null
) since the type of list is not known.
Foo
is typed on some unknown but specific type.