連想配列サンプルプログラムとして,英英辞書のプログラムを作りました.
辞書
下記のサンプルプログラムの putIntoDict() メソッドでは,HashMap へのエントリ(=見出し語と文章)の挿入を行う. putIntoDict() のパラメータは,2つの文字列である.一方は見出し語,もう一方は文章である.StringTokenizer で,改行コード単位で区切って,文字列配列を作る.(こうしているのは,メソッドの呼び出し側のプログラムを簡単に書けるようにするため).
printDict() メソッドでは,辞書の中身を全て表示することを行う.
package hoge.hoge.com;
import java.util.HashMap;
import java.util.StringTokenizer;
public class HashMapSample {
HashMap<String, String[]> dict;
public HashMapSample() {
dict = new HashMap<String, String[]>();
}
// 辞書への登録.キー(key)は文字列.info は文字列の配列だが,パラメータでは,各要素を改行コードで区切って渡す.
public void putIntoDict( String key, String info ) {
StringTokenizer st = new StringTokenizer(info, "\n");
int length = st.countTokens();
String [] result = new String[length];
for (int i = 0; i < length; i++) {
result[i] = st.nextToken();
}
dict.put( key, result );
}
public void printWord( Object key ) {
System.out.println( key + ":" );
for( int j = 0; j < ( (String [])(dict.get(key)).length ); j++ ) {
System.out.println( ((String [])dict.get(key))[j] );
}
}
public void printDict() {
Object [] keys = dict.keySet().toArray();
for( int i = 0; i < keys.length; i++ ) {
printWord( keys[i] );
}
}
public static void main(String[] args) {
HashMapSample map = new HashMapSample();
String str = "adj : appearing earlier in the same text; \"flaws in the above interpretation\"\n" +
"adv 1: at an earlier place; \"see above\"\n"+
"2: in or to a place that is higher";
map.putIntoDict( "above", str );
map.printDict();
return;
}
}