2016-11-19 45 views
0

我正在编写一个地址表单的测试。所以我需要有效的数据。Java中适当的容器/数据结构

我的第一种方法是返回HashMap<String, String>与此数据的方法。 (即m.put("city, "New York"))。

我不确定这是否适合我的情况下的数据结构。我只需要一个包含数据的容器,以便可以在方法中返回数据。属性的数量和名称是固定的,所以它们在运行时不会改变。所以我并不需要动态添加和删除元素的功能。

因此,我考虑实施一个名为AddressData或类似的类。通过创建AddressData -Objects,可以将所需的数据分配给类属性。所以我可以让它们公开或通过getter方法获取它们。

您认为如何?其他数据结构建议?

他们这样,我实现了它迄今:

public HashMap getValidData(String country){ 
    HashMap<String, String> data = new HashMap<String, String>(); 

    if(country.equals("USA")){ 
     data.put("firstname","John"); 
     data.put("lastname","Green"); 
     data.put("city","New York"); 
    } 
    else if(country.equals("Germany")){ 
     //add valid german address data 
    } 

    return data; 
} 

实施草案,一类:

class AddressData{ 
    private String firstname; 
    private String lastname; 
    private String city; 

    public AddressData(String country){ 
     if(country.equals("USA")){ 
      firstname="John"; 
      lastname="Green"; 
      city="New York"; 
     } 
     else if(country.equals("Germany")){ 
      //add valid german address data 
     } 
    } 

    public String getFirstname(){ return firstname; } 
    // other getters 
} 
+0

在散列表中,每个键必须是唯一的。 – SkrewEverything

+0

这是正确的。我的情况没有问题。关键字是AddressData类别,即名字,姓氏,城市......我不需要在一组数据中的两个城市。 – MrBrightside

+0

请在代码中提供您迄今为止所做的工作。所以我们可以修改并解释你。有很多方法可以设计出你甚至不理解的东西。 – SkrewEverything

回答

1

如果您有属性的固定列表,你应该创建一个代表表单类就像你建议的AddressData一样。

0

为了让代码更灵活,你不应该有String countryAddressData,否则,你最终会与许多if-else conditions处理许多国家,而那些countrycode作为重点和AddressData作为价值对象存储在HashMap作为如下图所示:

AddressData类:

public class AddressData { 

    private String firstname; 
    private String lastname; 
    private String city; 

    public AddressData(String firstname, String lastname, String city){ 
      this.firstname=firstname; 
      this.lastname=lastname; 
      this.city=city; 
    } 

    public String getFirstname(){ return firstname; } 
    // other getters 
} 

AddressData的用途:

HashMap<String, AddressData> data = new HashMap<String, AddressData>(); 
AddressData addressData1 = new AddressData("John", "Green", "New York"); 
data.put("USA", addressData1); 
//You can add other address data