【问题标题】:Is there a difference between initializing List and ArrayList? [duplicate]初始化 List 和 ArrayList 有区别吗? [复制]
【发布时间】:2020-11-25 03:45:04
【问题描述】:

我有代码:

List<Integer> grades = new ArrayList<Integer>();
ArrayList<Integer> grades1 = new ArrayList<>();

初始化ArrayList的第一种方式和第二种方式有什么区别?

【问题讨论】:

  • 你搜索过这个吗?在过去的一周里,我曾多次看到这里回答过同样的问题。
  • 通常您希望使用List&lt;Integer&gt; grades = new ArrayList&lt;Integer&gt;();,因为这可能允许您将成绩类型更改为不同类型的列表。

标签: java initialization


【解决方案1】:

ArrayList本质上是List的一种,也就是说,正如NomadMaker所指出的,ArrayLists可以被初始化为Lists。

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

如果您打算将grades 更改为其他类型的列表,则需要使用List&lt;&gt;,否则没有区别。

【讨论】:

  • 是的,有区别。有时,实现具有接口未指定的其他方法。为了利用您想要分配给实现类型(类名)而不是接口的那些。
猜你喜欢
  • 2010-11-06
  • 2013-01-31
  • 2015-11-08
  • 2014-03-16
  • 2014-07-22
  • 2017-05-08
相关资源
最近更新 更多