V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
anonymoustian
V2EX  ›  问与答

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

  •  
  •   anonymoustian · 2016-04-05 21:39:25 +08:00 · 1846 次点击
    这是一个创建于 2968 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    我想通过 类方法(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 命名为成员变量。

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

    4 条回复    2016-04-05 22:18:14 +08:00
    LossLess
        1
    LossLess  
       2016-04-05 21:56:59 +08:00   ❤️ 2
    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
        2
    Lonely  
       2016-04-05 22:15:18 +08:00   ❤️ 1
    一个就是楼上的方法。
    public class Test {
    private static HashSet set = initSet();
    private static HashSet initSet() {
    //do something
    }
    anonymoustian
        3
    anonymoustian  
    OP
       2016-04-05 22:17:55 +08:00
    @LossLess 谢谢!
    anonymoustian
        4
    anonymoustian  
    OP
       2016-04-05 22:18:14 +08:00
    @Lonely 谢谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1181 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 18:36 · PVG 02:36 · LAX 11:36 · JFK 14:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.