Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java assume type based on result?

Tags:

java

There is a code in Java:

import java.util.HashMap;
import java.util.Collection;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<Integer, String> langMap = new HashMap<>();
    langMap.put(1, "Java");
    langMap.put(2, "C#");
    Collection<String> values = langMap.values();
  }
}

In the last code line there is Collection<String>. Isn't <String> unnecessary because the type is assumed based on the values assigned from langMap?

like image 251
Tom Smykowski Avatar asked Jun 05 '26 00:06

Tom Smykowski


2 Answers

Isn't <String> unnecessary

No, it's necessary: without <String>, the type of the variable would be Collection, which is a raw type. Don't use raw types.

I suppose Java could have a notation for such contexts like Collection<>, similar to the diamond notation, but it doesn't.

You either have to use Collection<String>, or var in language versions which support it (11 and higher).

like image 147
Andy Turner Avatar answered Jun 07 '26 14:06

Andy Turner


From the doc The values() method of an HashMap return Collection<V>.

V is a generics that will be inferred to the type of the value of the HashMap that you declared.

var keyword

In Java 10 and later, you could use the var syntax to write :

var values = langMap.values();

…and the type of the Collection would be implicitly inferred. Here it would be inferred as Collection<String> since you declared the Map as Map<Integer, **String**>.

See this code run live at IdeOne.com.

See also JEP 286: Local-Variable Type Inference.

like image 38
jossefaz Avatar answered Jun 07 '26 12:06

jossefaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!