3

我有一个从数据库读取并在那里获取一些字符串的方法。根据我得到的信息,我将为另一个我已经知道的字符串覆盖该字符串。例如:

  • strstring
  • binbinary
  • 等等..

我的问题是,这样做的最佳做法是什么?当然,我已经考虑过如果...

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

一个预先定义了这些东西的文件,一个多维数组等。但这一切似乎都是一个新手,所以你有什么推荐的?什么是最好的方法?

4

3 回答 3

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);

您可以在此处阅读有关地图的更多信息

于 2013-03-25T18:47:02.833 回答
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
于 2013-03-25T18:47:45.497 回答
1

正如人们所建议的那样,地图是一个不错的选择。在这种情况下,我通常考虑的另一个选项是 Enum。它为您提供了为组合添加行为的额外功能。

于 2013-03-25T18:55:09.730 回答