运行效果:
代码:
package SY12.Test05;
import java.util.*;
public class Concordance {
Map map = new HashMap();//创建HashMap对象
//构造方法
public Concordance(String s) {
for (int i = 0; i < s.length(); ++i){
if(s.charAt(i) == ' ') continue;
add(s.charAt(i), i);
}
}
public void add(char c, int pos) {
Character key = new Character(c);
List l = (List)map.get(key);
if (l == null) {
l = new ArrayList();
map.put(key, l);
}
l.add(new Integer(pos));
}
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello World");//创建StringBuffer对象
for (int i = 0; i < args.length; ++ i)
sb.append(args[i]);//将命令行参数加到StringBuffer中
Concordance concordance = new Concordance(sb.toString());
System.out.println(concordance.map);//打印结果
}
}