只能使用一次getter方法

时间:2010-09-13 19:32:52

标签: java

我正在开发一个Java项目,我在下面的TextAnalyzer类中有getter方法:

public Hashtable<String, Double> getTotalFeatureOccurances() {
    return(feat_occur_total);
}//getTotalFeatureOccurances

我也有私有类变量:

private Hashtable<String, Double> feat_occur_total;

我使用getter,在hash中添加更多术语,然后想再次获取hash,但它总是返回空。更糟糕的是,如果我不从哈希中添加或删除任何内容,但是做了两次获取,我仍然会第二次收到并清空哈希。

这是我的主要代码:

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

2 个答案:

答案 0 :(得分:5)

此:

feat_occur_total.clear();

清除Hashtable。由于您返回了对原始变量的引用,因此您清除了Hashtable本身,而不是副本。因此,再次返回将返回已清除的Hashtable。

答案 1 :(得分:1)

您的getter返回对私有feat_occur_total字段的引用,而不是副本。在此之后,getter返回的TextAnalyzer.feat_occur_total引用和引用都引用相同的实例。您正在使用getter返回的引用调用clear(),这会清除顶部的代码段和TextAnalyzer实例引用的地图。