私はスタンフォード大学で CS106A コースを受講しており、課題の 1 つは、特定の都市間で利用可能なフライトのデータベースを構築することです。都市のクラスを作成しましたが、メソッドの呼び出しはaddDestination初めて機能し、2 番目の目的地が追加されると、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各行が "San Francisco -> New York" のような 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();
    }