List list = new ArrayList();

创建一个类型为字符串的List,该列表可以潜在地类型转换为任何其他类型的列表.这称为解耦.您正在将代码与接口的特定实现分离.它提供的优点是,在编写大量代码时,您可以在列表类型之间切换以满足您的喜好(速度,内存等),因为您的所有代码都可以将列表视为类型列表.您还可以将List作为参数传递并从函数中返回List.如果您对ArrayList不满意,稍后就可以更改那一行代码

List list = new ArrayList(); // old code

List list = new LinkedList(); // new code

// The rest of the code doesnt need changing

...

list = getList();

...

public List getList() {

List temporaryList;

...

return temporaryList;

}

public void changeList(List localListVariable) {}

并且您的程序将按预期运行.

另一方面,

ArrayList list = new ArrayList();

创建String类型的ArrayList,它不能用作任何其他类型的List(Vector,LinkedList等).因此,它受ArrayList可用的方法的约束.如果您现在想要更改所使用的列表类型,则必须在整个程序中更改所有函数参数和返回类型等(无论您何时必须创建ArrayList< String>以使用您的变量).

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐