Greetings to all! I read from Bruce Eckel about generics, I got the following code as an example:

package net.mindview.util; import java.util.*; public class New { public static <K,V> Map<K,V> map() { return new HashMap<K,V>(); } } public class LimitsOfInference { static void f(Map<Person, List<? extends Pet>> petPeople) {} public static void main(String[] args) { // f(New.map()); // Does not compile } } 

And an explanation:

Type inference doesn’t work for anything other than assignment. If you pass through the method of a new method, it will make it possible. This is a variable of type Object.

Nevertheless, I reproduced this code in the IDE, it was successfully compiled and launched. Is this a bug or is the information in the book out of date? I have jdk 8.

  • one
    but the message does not seem to say that it will not compile - Alexey Shimansky
  • Look at the commented line in the code. I understand that the author means a compilation error. - Oleg Martynov
  • ideone.com/I3kQUq - Qwertiy
  • 3
    @ Oleg Martynov is quite possibly the case really in the version. Looking what edition of the book you are reading. here in the 4th edition java 5 and 6 were considered. Starting from 7, it starts. so it’s rather outdated infa (1.6 - browxy.com - will not start, 1.8 - ideone.com/I3kQUq - starts) - Alexey Shimansky
  • @ Alexey Shimansky Thank you, you probably need to read something more relevant. - Oleg Martynov

1 answer 1

The problem is that you have Java 8 .

Tell the development environment that you need to build this for Java 6 , and you will see that the project is not really compiling.

It’s all a matter of diamond operators that were not yet in Java 6 , respectively, creating f(New.map()) , which is considered to be a map with two objecт , and it is expected to be parameterized with other Map types .

To understand the problem, let's take a simple example.

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

Here, after the sheet, a generic with a string, for some reason, is not displayed correctly ... This is quite acceptable for Java 8 , since Java 8 sees a parameterized sheet in the left part and adds the same string as a parameter in the left part of the generic left.

However, if you run it on Java 6 , then there will be a compilation error , explicit parameters of generics will be required

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

The same thing happens in your example.