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

人々が示唆しているように、地図は良い選択肢です。このシナリオで私が通常検討する他のオプションは列挙型です。組み合わせの動作を追加する追加機能を提供します。

于 2013-03-25T18:55:09.730 に答える