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?
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).
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 keywordIn 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With