2

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()
GhostCat
  • 137,827
  • 25
  • 176
  • 248
user157920
  • 43
  • 4
  • Do you mean `Collections.EMPTY_LIST` and `Collections.emptyList();` If so refer [here](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#EMPTY_LIST) and [here](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList()) – SomeDude Jun 19 '17 at 12:00
  • @JoeClay I have updated the question. – user157920 Jun 19 '17 at 12:01
  • @SteveSmith content updated. sorry for the trouble. – user157920 Jun 19 '17 at 12:02
  • 1
    The compiled result will be the same in both cases. It's just type checking for the compilation and your IDE. At the compilation, the generics stuff is removed. And therefore, it prevents to cast everytime you want to get something from the collection. – sjahan Jun 19 '17 at 12:04

1 Answers1

2

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Any word of explanation by the brave downvoter? I think my answer is spot on. – GhostCat Jun 19 '17 at 12:04
  • 1
    @Tom Aaaaa. That is why I couldnt find a link for it. Thanks! – GhostCat Jun 19 '17 at 12:08
  • Yeah, you'll find much more with "type witness" :D. Btw I've deleted the old comment, because it is obsolete now (I like to clean up). – Tom Jun 19 '17 at 12:09
  • @GhostCat thanks for the information. Can you tell me what happens if we are not providing type information then how the reference of one type is casted to point to object of other type. – user157920 Jun 19 '17 at 12:21
  • @user157920 You are welcome. I updated my answer again; hope that helps. – GhostCat Jun 19 '17 at 12:31