我正在开发一个 Java 项目,其中我在 TextAnalyzer 类中有下面的 getter 方法:
public Hashtable<String, Double> getTotalFeatureOccurances() {
return(feat_occur_total);
}//getTotalFeatureOccurances
我还有私有(private)类变量:
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
这是整个类(class):
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
最佳答案
这个:
feat_occur_total.clear();
清除哈希表。由于您返回了对原始变量的引用,因此您清除了 Hashtable 本身,而不是副本。所以再次返回它会返回清除的哈希表。
关于java - 只能使用一次 getter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3703729/