可能重复:
列表与ArrayList
之间的区别
ArrayList al = new ArrayList()
Run Code Online (Sandbox Code Playgroud)
和
List al = new ArrayList() ?
Run Code Online (Sandbox Code Playgroud)
And*_*s_D 10
没有,从创作的角度来看.两者都创建了一个实例ArrayList.
不同之处在于,在第二个示例中,al允许访问在List接口上实现的所有方法,而在第一个示例中,al允许访问类的所有(可访问的)方法和字段ArrayList.
一个实际的经验法则:使用第二种模式.如果您需要从ArrayList实现中获得额外的好处,那么您总是可以投射:
List list = new ArrayList();
// do some adds/removes/... on the list
((ArrayList) list).trimToSize();
Run Code Online (Sandbox Code Playgroud)
它称为编程接口.假设您需要list从方法中返回此值.因此调用代码可以将其转换为List变量.
public ArrayList getList() {
ArrayList list = new ArrayList();
// do something with the list here
return list;
}
Run Code Online (Sandbox Code Playgroud)
还有这个,
public List getList() {
List list = new ArrayList();
// do something with the list here
return list;
}
Run Code Online (Sandbox Code Playgroud)
现在对于后一种方法,调用代码可以将返回的列表放在List类型变量中.你可以稍后轻易地决定,出于某种原因,这样的事情,
public List getList() {
List list = new LinkedList();
// do something with the list here
return list;
}
Run Code Online (Sandbox Code Playgroud)
调用代码没有变化,而前者需要更改返回类型,这最终会搞砸调用代码.
| 归档时间: |
|
| 查看次数: |
18762 次 |
| 最近记录: |