2014-01-16 124 views
0

我有2個豆類 - 國家&城市。我需要在鄉村班級中保留城市列表。並且,當我設置城市信息時,我需要設置國家名稱,因此也需要城市級別內的國家。怎麼做? 下面是代碼:如何在兩個模型類別中創建列表

Country.java

public class Country { 

private String name; 
private String about; 
ArrayList<City> cities; 

public Country() 
{ 
    cities = new ArrayList<City>(); 
} 

public Country(String name, String about) 
{ 
    this.name= name; 
    this.about = about; 
} 


public int getNoOfCities() 
{ 
    return cities.size(); 
} 


public long getNoOfCitizens() 
{ Long aPop= 0L; 
    //Long aPopulation = cities.get 
    for(City aCity: cities) 
    { 
     aPop += aCity.getPopulation(); 
    } 
    return aPop; 
} 



public String getName(){ 
    return name; 

} 
public String getAbout(){ 
    return about; 
} 
} 

City.java

public class City { 

    private String name; 
    private String about; 
    private Long population; 

    public City(String name, String about, Long population) 
    { 
     this.name= name; 
     this.name = about; 
     this.population = population; 


    } 
    public String getName(){ 
     return name; 

    } 
    public String getAbout(){ 
     return about; 

    } 
    public Long getPopulation(){ 
     return population; 
    } 
} 

我該怎麼解決呢?有人告訴我像ViewObject的東西,但不知道它是什麼或它是否會解決。幫幫我吧:-)

國家進入/細節UI 1.名稱(輸入) 2.關於(輸入)每個國家 4. 3.列出以便在ListView每個國家 - 細節UI(細節UI),其將具有: 4.1。名稱 4.2該國家下的城市數量 4.3。人口在這個國家數(這將是所有城市的人口的國家根據總和)

市錄入UI 1.名稱(輸入) 2.關於(輸入) 3。人口(輸入) 4.國家(下拉)

回答

0

我不知道我完全理解這個問題,但我能想到的最簡單的辦法是增加參照國家的城市。如果你仔細想一想,這很有道理 - 每個城市都在一個國家,所以不應該有一個沒有國家的城市。

public class City { 

private String name; 
private String about; 
private Long population; 
private Country country; 

public City(String name, String about, Long population, Country country) 
{ 
    this.name= name; 
    this.name = about; 
    this.population = population; 
    this.country=country; 
    country.addCity(this); 
} 
+0

我已在國家內有城市列表。我聽說它的糟糕的概念在使用相反的引用回到另一個類(如在city.java中的國家參考) –

+0

請解釋這句話「當我設置城市信息時,我需要設置國家名稱」。哪裏?你想在城市的一個領域設置國家名稱? – NeplatnyUdaj

0

您可以使用模型工廠類。它們可以用來填充和創建控制器的模型。 e.g:

public class CountryModelFactory { 

    public static Country populateCountryModel() { 
     // code to populate the Country model. 
     // then return the Country model. 
    } 
} 

使用Model廠型類的優點是,可以通過介質然後可以填充取決於請求的數相似模型的來自控制器的模型分離。

相關問題