2014-01-16 125 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厂型类的优点是,可以通过介质然后可以填充取决于请求的数相似模型的来自控制器的模型分离。

相关问题