Java 8 Incompatible Types

Here is a simple code

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SimpleTest {

    public static void main(String[] args) {
    final ArrayList<Map<String, Object>> maps = newArrayList(
        createMap("1", "a", Collections.EMPTY_MAP, Collections.EMPTY_MAP),
        createMap("2", "b", Collections.EMPTY_MAP, Collections.EMPTY_MAP),
        createMap("3", "c", Collections.EMPTY_MAP, Collections.EMPTY_MAP)
    ); 

    System.out.println(" maps = " + maps);
    }

    public static Map<String, Object> createMap(String value1, String value2, Map<String, Object> object1, Map<String, Object> object2) {
       Map<String, Object> map = new HashMap<>();
       map.put("value1", value1);
       map.put("value1", value1);
       map.put("object1", object1);
       map.put("object2", object2);
       return map;
    }    

    public static <E> ArrayList<E> newArrayList(E... elements) {
    ArrayList<E> list = new ArrayList<E>(elements.length);
    Collections.addAll(list, elements);
    return list;
    }
}

When JAVA_HOME points to JDK 8 and I use javac -source 1.7 SimpleTest.java, I get

SimpleTest.java:9: error: incompatible types: ArrayList<Map> cannot be converted to ArrayList<Map<String,Object>>
        final ArrayList<Map<String, Object>> maps = newArrayList(
                                                                ^

When I use the -source 1.8or no option -source, everything works fine. Now that JAVA_HOME points to JDK 7, the code always compiles whether I use it -source 1.7or not.

This question originally concerned a piece of software in which the POM file has <source>both <target>, installed on 1.7, and the build was unsuccessful in JDK 8, but was ok on JDK 7.

Now for the question - what makes this happen? It seems to me that this is some important kind. Why compilation on JDK 8 s sourceinstalled on 1.7failed?

+2
1

, :

public class Test2 {
    @SafeVarargs
    static <T> ArrayList<T> newArrayList(T... arg) {
        return new ArrayList<T>(Arrays.asList(arg));
    }
    private final List<Map<String, Object>> maps = newArrayList(
        createMap(null, Collections.EMPTY_MAP)
     );

    public static Map<String, Object> createMap(String id, Map<String,String> m) {
        return null;
    }
}

javac jdk1.7, javac jdk1.8 -source 1.7.

, javac jdk1.8 , , , -source 1.7 , , Java 7 . , .

Collections.EMPTY_MAP, Collections.<String,String>emptyMap(), Map createMap, , Map.

JLS §15.12.2.6:

:

  • void, .

  • , , - (§4.6) , .

...

, () javac jdk1.7. , ,

public static <T> Map<String, Object> createMap(String id, Map<String,String> m)

. jdk1.7 . .


, , Java 8 , target, .

+4

Source: https://habr.com/ru/post/1624016/


All Articles