2013-03-25 15 views
3

我有一個方法,從數據庫中讀取並獲取一些字符串。根據我得到的結果,我會重寫那個我已經知道的另一個字符串。例如:在java中的方法的良好做法

  • strstring
  • binbinary
  • 等..

我的問題是,什麼是這樣做的最佳做法?當然,我已經想到了,如果的...

if (str.equals("str")) 
    str = "string"; 

有這種事情預先定義的文件,多維數組,等等。但是,這一切似乎相當新手,那麼你有什麼建議?什麼是最好的方法?

+3

那你動態加載的地圖怎麼樣 – Frank 2013-03-25 18:46:02

回答

8

使用地圖:

// create a map that maps abbreviated strings to their replacement text 
Map<String, String> abbreviationMap = new HashMap<String, String>(); 

// populate the map with some values 
abbreviationMap.put("str", "string"); 
abbreviationMap.put("bin", "binary"); 
abbreviationMap.put("txt", "text"); 

// get a string from the database and replace it with the value from the map 
String fromDB = // get string from database 
String fullText = abbreviationMap.get(fromDB); 

你可以read more about Maps here

+0

要回答的問題,真的很有幫助,現在將是我的解決方案,但是,我必須創建一個新的代碼,每次我有一個新的字符串添加.. – user1851366 2013-03-25 18:52:57

+1

你可以在實用程序類中也使用ResourceBundle或Properties文件或靜態構造函數。我可能會在某個類中聲明一個靜態的最終地圖來保存這些信息。實際上,如果可能的話,我可能會使用數據庫來保存縮寫。當您的應用程序初始化時,您可以將數據從數據庫讀入某張地圖。 – jahroy 2013-03-25 18:57:01

+1

您可以將所有信息存儲在屬性文件或XML格式的文件中,當您的應用程序啓動或運行時獲取此信息並形成您的地圖 – 2013-03-25 18:57:29

2

你可以使用的地圖,例如:

Map<String, String> map = new HashMap<String, String>(); 
map.put("str", "string"); 
map.put("bin", "binary"); 

// ... 

String input = ...; 
String output = map.get(input); // this could be null, if it doesn't exist in the map 
1

地圖是一個不錯的選擇,因爲人都建議。我通常在這種情況下考慮的另一個選項是Enum。它爲您提供了添加組合行爲的額外功能。