2016-11-19 46 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