use*_*750 1 java collections arraylist
我正在实现一个包含对象的ArrayList的接口.它使用以下代码将ArrayList作为类型Collection返回.
public class NetworkImpl implements Network {
private Collection<Station> stationList = new ArrayList<Station>();
public Collection<Station> getStations() {
return stationList;
}
}
Run Code Online (Sandbox Code Playgroud)
在我填充了stationList ArrayList后,我无法直接访问各个站点,我将如何进行此操作?我尝试了以下但它不起作用:
public class Test {
public static void main(String args[]) {
Network newNetwork = new NetworkImpl(); // This is implemented and populated elsewhere
newNetwork.getStations().get(0);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要随机访问Collection的元素,getStations()则应返回a List<Station>而不是a Collection<Station>.
当然你可以将返回的Collection转换为List或者ArrayList(在使用之后instanceof验证它的类型),但是如果方法返回a Collection,则无法保证其实现在一天内不会改变以返回a Set,这将破坏依赖于的代码随机访问.
另一种选择是构造一个ArrayList基于返回的Collection- new ArrayList<Station>(newNetwork.getStations()),这将保证您最终得到一个ArrayList,无论Collection该方法返回什么类型.