4

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);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • You might want to have a look at http://stackoverflow.com/questions/503721/generics-in-java-using-wildcards – assylias Feb 06 '12 at 18:25

1 Answers1

6

There are multiple advantages.

  • They won't produce compiler warnings like using the raw type would
  • 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 Numbers. 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.

  • They document something completely different than a raw type, namely that Foo is typed on some unknown but specific type.
Mark Peters
  • 80,126
  • 17
  • 159
  • 190