Java 工具类中想使用 static 方法,但是方法中需要查询 HashSet,不通过实例化怎么去封装这个类?

2016-04-05 21:39:25 +08:00
 anonymoustian

我想封装一个计算类,计算一个字符串中连续辅音字母的比例。

我想通过 类方法(static) 而不是 实例化类去执行这个方法,

于是我这么写了代码:

public static double calcConsecConsonantRatio(String str) {
    int consonantCount = 0;
    int flag = 0;
    str = str.toLowerCase();
    HashSet<Character> hs = new HashSet<Character>();
    char[] consonant = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'};
    for (int i = 0; i < consonant.length; i++) {
        hs.add(consonant[i]);
    }
    for (int i = 0; i < str.length(); i++) {
        if (hs.contains(str.charAt(i))) flag++;
        else {
            if (flag != 1) consonantCount += flag;
            flag = 0;
        }
    }
    consonantCount += flag;
    return (double) consonantCount / str.length();
}

但是这样有一个问题就是每次调用这个方法的话 就需要重新执行一遍 入 Hashset 的操作,

但是因为是 static 方法 所以无法将该 Hashset 命名为成员变量。

我有很多这样的集合,比如 元音集合、数字集合等等,这些都不知道怎么办,请教一下大家

1849 次点击
所在节点    问与答
4 条回复
LossLess
2016-04-05 21:56:59 +08:00
public class Test {
private static HashSet<Character> set = new HashSet<>();
private static Character[] str = {'a', 'b', 'c'};
static {
set.addAll(Arrays.asList(str));
}
private static void test() {
System.out.println(set);
}

public static void main(String[] args) {
test();
}
}
可以通过静态代码快初始化
Lonely
2016-04-05 22:15:18 +08:00
一个就是楼上的方法。
public class Test {
private static HashSet set = initSet();
private static HashSet initSet() {
//do something
}
anonymoustian
2016-04-05 22:17:55 +08:00
@LossLess 谢谢!
anonymoustian
2016-04-05 22:18:14 +08:00
@Lonely 谢谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/268800

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX