代码之家  ›  专栏  ›  技术社区  ›  kumarmo2

无法理解如何在java中定义列表列表[重复]

  •  1
  • kumarmo2  · 技术社区  · 7 年前

    我想理解这两个定义之间的区别,以及为什么正确的一个是正确的,错误的是错误的。

    List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();  
    

     try2.java:8: error: incompatible types: ArrayList<ArrayList<Integer>> cannot be
    converted to List<List<Integer>>
                    List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
    

    正在工作的一个:

    List<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
    

    注:

    List<Integer> arr = new ArrayList<Integer>();  
    

    :

    现在我只想了解一下 List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();

    2 回复  |  直到 7 年前
        1
  •  6
  •   GhostCat    7 年前

    你不需要这些:

    List<List<Whatever>> items = new ArrayList<>();
    

    List<Whatever> innerItems = new ArrayList<>();
    items.add(innerItems);
    

    例如原因是:集合是

    其中一个原因是泛型实际上是使用 。这意味着:实际的列表实现对您在源代码中使用的泛型类型一无所知。它只处理 Object 从这个意义上讲,实现不可能“知道”新列表应该包含 List<Whatever>

        2
  •  4
  •   Eran    7 年前

    正如GhostCat所建议的那样,您可以使用菱形运算符,让编译器担心正确的类型。

    但是,如果您想了解正确的类型,请使用:

    List<List<Integer>> arr2 = new ArrayList<List<Integer>>(); 
    

    List 关于某件事(让我们暂时忘记,某件事碰巧是一个 List<Integer> 列表 ArrayList 在这种情况下。所以你创建了一个 关于某件事。

    元素类型(我所谓的“某物”)- 列表(<);整数>

    ,您需要创建实现

    List<Integer> inner = new ArrayList<Integer>();
    arr2.add(inner);