Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Does Java assume type based on result?

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?

question from:https://stackoverflow.com/questions/65873194/does-java-assume-type-based-on-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...