0

Sometimes I see java code which looks like

Class<?>

and I don't understand the proper meaning of it.

If I see something like:

ComboBox<Order> box = new ComboBox<>();

then its clear that box can only contain Objects from the class Order, but what about <?>? Is it equal to or something completely different?

BlackFlag
  • 150
  • 8

1 Answers1

6

It's called a wildcard, it just means you don't need to specify the generic type. It is sometimes useful, but should not be used in general. One case where you can use it safely is when you use a type bound :

public void withWildCard(List<? extends Collection<Integer>> collections) { 
    ...
}

public void withoutWildCard(List<Collection<Integer>> collections) { 
    ...
}

List<Collection<Integer>> listOfCollections;
withWildcard(listOfCollections); // valid call
withoutWildcard(listOfCollections); // valid call

List<List<Integer>> listOfLists;
withWildcard(listOfLists); // valid call becase List is a subclass of Collection
withoutWildcard(listOfLists); // invalid call, does not compile because List does not match Collection

By the way, the snippet in your question is wrong. It should be

ComboBox<Order> box = new ComboBox<>();

If you don't specify the generic type in the declaration side, the compiler won't be able to infer the type of the diamond operator (<>).

Dici
  • 25,226
  • 7
  • 41
  • 82
  • 1
    please check your answer. I don't see any difference between the two methods – Kachna Aug 19 '15 at 23:56
  • Haha, copy pasting is bad... Thanks, I fixed it – Dici Aug 20 '15 at 00:03
  • So is '>' equal to ''? – BlackFlag Aug 20 '15 at 09:37
  • 1
    This is how it is going to be compiled, but it is not really equivalent. For example you cannot do `List x = ...; List> y = x`. Actually I tried some things with `List>` and I could not add anything to it whereas it compiles fine for `List`. This makes me think that ? should only be used when there is a bound on the type (for example `? super A`, otherwise you have absolutely no clue on the type – Dici Aug 20 '15 at 14:09