【问题标题】:How to create ArrayList of ArrayLists so that it fits the programe to interface principle如何创建 ArrayLists 的 ArrayList 使其符合程序接口原则
【发布时间】:2014-09-22 03:43:05
【问题描述】:

我知道这个问题已经被问过了,但我从不同的角度来看待它。 提供了generic type for ArrayList of ArrayLists 是什么的答案。但是,我正在寻找最佳实践并编程接口。然后我想出了以下三个选项。

问题:

  1. 为什么选项 1 是编译错误?为什么无法进行转换?

  2. 首选选项 2 或 3 中的哪一个?在哪里?

  3. 在选项3中,为什么界面“列表”出现在语句的右侧?请为此提供适当的答案。我需要了解这些嵌套的通用定义。

     1) List<List<Integer>> arList1 = new ArrayList<ArrayList<Integer>>();
     2) List<ArrayList<Integer>> arList2 = new ArrayList<ArrayList<Integer>>();
     3) List<List<Integer>> arList3 = new ArrayList<List<Integer>>();
    

【问题讨论】:

    标签: java list arraylist


    【解决方案1】:
    1. 这段代码:

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

      是一个编译错误,因为List&lt;List&lt;Integer&gt;&gt; 可以合法地持有LinkedList&lt;Integer&gt;,但赋值的右侧不能。泛型不是协变的。 (见优秀的article on generics by Brian Goetz。)

    2. 我更喜欢 3,除非我想明确要求添加到 arList2 的列表必须是 ArrayList 的实例。虽然这样的要求很少见,但可能会出现。

    3. 在 Java 7 中,您不需要这样做。你可以写:

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

      并且编译器将在右侧填写List&lt;Integer&gt; 作为泛型类型参数。在 Java 6 及更早版本中,您需要为构造函数调用显式提供与赋值左侧的泛型参数兼容的泛型参数。

    【讨论】:

      【解决方案2】:

      选项 1 是编译错误,因为类型不兼容。实际上,您可以将不是ArrayListList 放入List&lt;List&lt;Integer&gt;&gt;,但不能放入ArrayList&lt;ArrayList&lt;Integer&gt;&gt;。这就是为什么List 出现在选项 3 的右侧。

      选项 3 是首选,因为它通过接口引用对象。请参阅 Joshua Bloch,Effective Java:编程语言指南,第 34 条。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-14
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 2021-02-21
        • 1970-01-01
        • 2012-01-10
        • 2014-01-18
        相关资源
        最近更新 更多