我的工作中,我有下面的getter方法的类TextAnalyzer Java项目:只能使用getter方法一旦
public Hashtable<String, Double> getTotalFeatureOccurances() {
return(feat_occur_total);
}//getTotalFeatureOccurances
我也有私有类变量:
private Hashtable<String, Double> feat_occur_total;
我使用getter,在散列中添加更多条件,然后再次获取散列,但总是回到空。更糟糕的是,如果我不添加或删除哈希中的任何内容,但有两次获得,我仍然会第二次接收并清空哈希。
这是我的主要代码:
TextAnalyzer ta = new TextAnalyzer();
feat_occur_cat = ta.wordOccurancesCount(text, features);
feat_occur_total = ta.getTotalFeatureOccurances();
Enumeration<Double> e = feat_occur_total.elements();
while(e.hasMoreElements()) {
System.out.println(e.nextElement());
}//while
feat_occur_total.clear();
feat_occur_total = ta.getTotalFeatureOccurances();
e = feat_occur_total.elements();
System.out.println("\n\nSECOND GET\n\n");
while(e.hasMoreElements()) {
System.out.println(e.nextElement());
}//while
我得到的输出:
2.0
1.0
5.0
1.0
1.0
3.0
2.0
3.0
SECOND GET
这里是整个类:
public class TextAnalyzer {
TextAnalyzer() {
this.feat_occur_total = new Hashtable<String, Double>();
}
public String[][] wordOccurancesCount(String text, Vector<String> features) {
String[][] occur = new String[features.size()][features.size()];
for(int ndx=0; ndx<features.size(); ndx++) {
int count=0;
Pattern p = Pattern.compile("(?:^|\\s+|\\()\\s*(" + features.elementAt(ndx).trim() + ")\\w*(?:,|\\.|\\)|\\s|$)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.CANON_EQ);
Matcher m = p.matcher(text);
m.usePattern(p);
while(m.find())
count++;
occur[ndx][0] = features.elementAt(ndx);
occur[ndx][1] = String.valueOf(count);
if(this.feat_occur_total.containsKey(features.elementAt(ndx))) {
double temp = this.feat_occur_total.get(features.elementAt(ndx));
temp += count;
this.feat_occur_total.put(features.elementAt(ndx), temp);
}//if
else {
this.feat_occur_total.put(features.elementAt(ndx), Double.valueOf(count));
}//else
}//for
return(occur);
}//word
public Hashtable<String, Double> getTotalFeatureOccurances() {
return(feat_occur_total);
}//getTotalFeatureOccurances
private Hashtable<String, Double> feat_occur_total;
}//TextAnalyzer
btw Hashtable已过时 - 优先使用HashMap而不是单线程代码,否则使用ConcurrentHashMap。 – 2010-09-13 19:43:21
这可能只是迂腐,但如果你创建了散列表,并且永远不要改变你的类中的私人引用,它也应该是“最终的”。这可以让你清楚你对这个类的用户的意图,最终的变量允许编译器执行它可能无法执行的优化。 – 2010-09-13 19:44:35