나는 스탠포드에서 CS106A 과정을 수강하고 있는데, 그 중 하나는 특정 도시간에 이용 가능한 항공편 데이터베이스를 구축하는 것입니다. 도시에 대한 수업을 썼지 만 addDestination
메서드를 호출하면 처음으로 작동하고 두 번째 대상이 추가되면 ArrayList
이 비어있게됩니다. 왜? 이 사람이 정말로 나를 잡았다. 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();
}
을 당신이 잘못의 ArrayList를 사용하는 것을 의미하지 않는다? – mre
이것은 귀하의 질문에 대한 대답이 아니지만, 일반적인 프로그래밍 예절에서는 객체 변수를 맨 아래가 아닌 객체의 맨 위에 놓아야합니다. 또한 클래스 자체가 아니라 생성자에서 대상 ArrayList를 초기화해야합니다. 실제로 문제가 해결 될 수도 있지만 확실하지 않습니다. – MattS
'.addDestination()'과'.destIter()'에 대한 호출을 보여줄 수 있습니까? – Tenner