What does <> in Java mean?

81 Views Asked by At

Looking at a library called mongojack 3.0 - https://github.com/mongojack/mongojack. This library contains a file called JacksonMongoCollection.java It has a method...

  public JacksonCollectionKey<TResult> getCollectionKey() {
        return new JacksonCollectionKey<>(getMongoCollection().getNamespace().getDatabaseName(), getMongoCollection().getNamespace().getCollectionName(), getValueClass());
    }

This returns JacksonCollectionKey<>

This library compiles fine.

I have not seen an empty generic type definition before. How does this work?

2

There are 2 best solutions below

0
ardenit On BEST ANSWER

Empty generic type brackets are used where generic type can be inferred from context by compiler. In your case, compiler will insert TResult into empty brackets.

0
cameron1024 On

This is a an example of "Type Inference" in Java. In certain situations, explicit type information can be omitted, when it is otherwise obvious what the missing type is.

In your example, the method returns JacksonCollectionKey<TResult>, and as such, it is not necessary to specify the type parameter, since it is given by the return type.

Another common example is:

List<String> list = new ArrayList<>();