user157920
user157920

Reputation: 43

java generic way of calling method vs normal calling

Can someone tell me the difference between calling the same function by two different ways and what exactly compiler does in both the cases; like:

  1. Collections.emptyList()
  2. Collections.<Integer>emptyList()

Upvotes: 2

Views: 125

Answers (1)

GhostCat
GhostCat

Reputation: 140525

The second option is giving a so called type witness.

In other words: you, the programmer give the compiler a hint to understand the generic return type that needs to be used here.

This feature was more important before Java8; simply because type inference wasn't "good enough" early on. Therefore Java syntax allows to specify the generic type this way.

With Java8, type inference has been dramatically improved; thus the need to give type hints is way smaller today.

In other words: most of the time, the compiler can detect that emptyList() is supposed to return a List<Integer> for example. In situations where the compiler is unable to do so; <Integer>emptyList() tells it what is expected.

The compiled output should be the same in both cases. And the thing to remember is: don't use a type witness unless you have to.

In other words: you write your code without using the type witness feature. Only when the compiler gives you an error that can only be resolved by using a type witness, then you use it.

See here or there for further reading.

Upvotes: 2

Related Questions