84. Combining LVTI and the diamond operator

As a rule of thumb, LVTI combined with the diamond operator may result in unexpected inferred types if the information that's needed for inferring the expected type is not present in the right-hand side.

Before JDK 7, that is, Project Coin, List<String> would be declared as follows:

List<String> players = new ArrayList<String>();

Basically, the preceding example explicitly specifies the generic class's instantiation parameter type. Starting with JDK 7, Project Coin introduced the diamond operator, which is capable of inferring the generic class instantiation parameter type, as follows:

List<String> players = new ArrayList<>();

Now, if we think about this example in terms of LVTI, we will get the following result:

var playerList = new ArrayList<>();

But what will be the inferred type now? Well, we have a problem because the inferred type will be ArrayList<Object>, not ArrayList<String>. The explanation is quite obvious: the information that's needed for inferring the expected type (String) is not present (notice that there is no String type mentioned in the right-hand side). This instructs LVTI to infer the type that is the broadest applicable type, which, in this case, is Object.

But if ArrayList<Object> was not our intention, then we need a solution to this problem. The solution is to provide the information that's needed for inferring the expected type, as follows:

var playerList = new ArrayList<String>();

Now, the inferred type is ArrayList<String>. The type can be inferred indirectly as well. See the following example:

var playerStack = new ArrayDeque<String>();

// inferred as ArrayList<String>
var playerList = new ArrayList<>(playerStack);

It can also be inferred indirectly in the following way:

Player p1 = new Player();
Player p2 = new Player();
var listOfPlayer = List.of(p1, p2); // inferred as List<Player>

// Don't do this!
var listOfPlayer = new ArrayList<>(); // inferred as ArrayList<Object>
listOfPlayer.add(p1);
listOfPlayer.add(p2);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset