barrypicker
barrypicker

Reputation: 10088

What does <> in Java mean?

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?

Upvotes: 1

Views: 83

Answers (2)

cameron1024
cameron1024

Reputation: 10136

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<>();

Upvotes: 2

ardenit
ardenit

Reputation: 3890

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.

Upvotes: 2

Related Questions