Java - Type Inference in Generic Object Creation


Consider the following statement:

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

You can rewrite the above statement in Java 7 and later as shown:
List<String> list = new ArrayList<>();

<> is called diamond operator.


Create the two lists, list1 of List<String> type and list2 of List<Integer> type.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list1 = Arrays.asList("A", "B");
    List<Integer> list2 = Arrays.asList(9, 19, 1969);

    List<String> list3 = new ArrayList<>(list1); // Inferred type is String
    List<String> list4 = new ArrayList<>(list2); // A compile-time error

    List<String> list5 = new ArrayList<>(); // Inferred type is String


To fix the compile time error

List<Integer> list4 = new ArrayList<>(list2); // A compile-time error