2

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?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236

3 Answers3

7

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

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
4

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
jossefaz
  • 3,312
  • 4
  • 17
  • 40
1

To say that it is unnecessary is not true, since According to your code you are trying to get the Set( Collection) of values from map .so to define the data type of this collection ( i.e data type of information that collection will be storing) will prevent any further error and makes it a clean. Otherwise, it might show a format exception. for instance, take this example when you want to store a value of Map of name 'map' containing the values of the integer data type.

// to get all the value of a map

Collection values = map.values();

// this convert your collection of values into any further collection // like ArrayList I have done here

ArrayList listOfValues = new ArrayList(values);

*****this line of code taken from my GitHub repo link is given down below line 26 , 27 . https://github.com/gulab786-SRG/Gfg_Solution/blob/master/gfg/Maximum%20_Width_of_Tree.java

Gulab_786
  • 31
  • 3