我正在学习斯坦福大学的 CS106A 课程,其中一项任务是建立一个特定城市之间可用航班的数据库。我为一个城市编写了一个类,但addDestination
第一次调用该方法有效,当添加第二个目的地时,ArrayList
最终为空。为什么?这个真让我着迷。
import java.util.*;
//class for a city. destinations are stored in an ArrayList
public class City {
//Constructor
public City(String name){
CityName = name;
}
//returns the name of the city
public String getName(){
return CityName;
}
// takes in a destination and adds it to the ArrayList unless
//the destination already exists in which case it returns false.
public boolean addDestination(String destination){
if (destinations.indexOf(destination)==-1){
destinations.add(destination);
return true;
}
else return false;
}
public Iterator<String> destIter(){
Iterator<String> it =destinations.iterator();
return it;
}
private ArrayList<String> destinations = new ArrayList<String>();
private String CityName;
}
这是创建城市数据库的代码。hm
是一个HashMap
,它读取一个 txt 文件,其中每一行类似于“旧金山 - >纽约”
BufferedReader rd = new BufferedReader(new FileReader(FileName));
String line = "";
while (line!=null){
if (line.indexOf("->")!=-1){
String From = line.substring(0, line.indexOf("->")-1);
String To = line.substring(line.indexOf('>')+2);
City city = new City(From);
if (hm.containsKey(From)==false)hm.put(From, city);
hm.get(From).addDestination(To);
}
line = rd.readLine();
}