首先这是一项任务,所以我更需要帮助然后编码答案(不想作弊!)。我的任务是创建一个处理火车/铁路车站网络的程序。我坚持的部分添加了站点,它们的连接,并将这些连接作为字符串数组列表返回。我已经包含了我到目前为止的代码,以及分配的摘录(与我现在的部分相关)。我整个周末一直都在苦苦挣扎,所以任何帮助都会非常感激。
这只是我需要编辑的界面的实现,即“MyNetwork”类。我只是觉得自己已经走了一圈,甚至可能没有从右脚站起来?
来自作业;
创建一个实现网络接口的MyNetwork类。
此类的getConnections方法应返回一个数组,该数组仅包含直接连接到fromStation参数的那些工作站。 提示1:您可以使用HashMap执行此操作,其中键是字符串(表示站点),值是字符串的数组列表(表示直接连接的站点)。
提示2:虽然getConnections方法返回一个字符串数组,但最好将HashMap中的值作为字符串的数组列表
界面;
public interface Network {
/**
* Add a station to the network.
* @param station The station to be added.
*/
public void addStation(String station);
/**
* Add a direct connection from one station to another.
* @pre both fromStation and toStation have already been added by the method
* addStation.
* @param fromStation The station from which the connection begins.
* @param toStation The station at which the connection ends.
*/
public void addConnection(String fromStation, String toStation);
/**
* Get a list of all stations directly connected to a given station.
* @pre fromStation has been added to the network by the method addStation.
* @param fromStation
* @return A list of all the stations to which there is a direct connection
* from fromStation.
*/
public String[] getConnections(String fromStation);
/**
* Search for a station in the network.
* @param station Station to be searched for,
* @return true if the Station exists in the network, false otherwise.
*/
public boolean hasStation(String station);
/**
* Get all stations in the network.
* @return An array containing all the stations in the network, with no
* duplicates.
*/
public String[] getStations();
实施:
public class MyNetwork implements Network {
@Override
public void addStation(String station) {
ArrayList<String> Stations = new ArrayList<>();
Stations.add(station);
}
@Override
public void addConnection(String fromStation, String toStation) {
Map<String,String> Connections = new HashMap<>();
Connections.put(fromStation, toStation);
}
@Override
public String[] getConnections(String fromStation) {
return null; // dummy value!
}
@Override
public boolean hasStation(String station) {
return false; // dummy value!
}
@Override
public String[] getStations() {
return null; // dummy value!
}
}
答案 0 :(得分:0)
您的网络需要拥有一个状态,使用一个或多个实例字段。
原样,它没有任何状态。每个方法都创建一个List或Map类型的局部变量,向此List或Map添加一些内容,然后返回。因此List或Map直接超出范围并被垃圾收集。
private Map<String, List<String>> stations = new HashMap<>();
// now all your methods should use the above map.
请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html