在静态方法类中的构造方法 [英] Constructor in a class of static methods

查看:257
本文介绍了在静态方法类中的构造方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态方法类,可以在类中保存的地图上执行,我想在调用类时设置地图。我试过使用一个私人导师,但它不是被叫。我的代码的相关部分是:

I've got a class of static methods that can be performed on a map held within the class, and I want the map to be set up when the class is called. I've tried using a private contructor, but it isn't being called. The relevant parts of my code are:

public class MyClass
{
    private static final String KEYS = "ABC";
    private static final String[] DATA = {"AAA", "BBB", "CCC"};
    private static HashMap<Character, String> myMap;

    private MyClass() {
        System.out.println("Running constructor");
        populateMyMap();
    }

    private static void populateMyMap() {
        myMap = new HashMap<Character, String>();
        for (int i=0; i < KEYS.length; i++) {
            myMap.put(KEYS.charAt(i), DATA[i]);
        }
    }

    //various static methods
}

私人构造函数是否正确的使用在这里,如果是,我做错了什么?

Is a private constructor the right thing to be using here, and if so what am I doing wrong?

如果这是一个重复,我尝试搜索答案,但我不知道要搜索的内容。

Sorry if this is a duplicate; I've tried searching for answers, but I'm not sure what to search for!

推荐答案

静态初始化块在其他几个答案中提到。但实际上我发现在野外更常见的以下成语:

The static initializer block has been mentioned in several other answers. But practically I find the following idiom more frequently in the wild:

public class MyClass
{
    private static HashMap<Character, String> myMap = createMyMap();

    private static HashMap<Character, String> createMyMap() {
        HashMap<Character, String> myTmpMap = new HashMap<Character, String>();
        for (int i=0; i < KEYS.length; i++) {
            myTmpMap.put(KEYS.charAt(i), DATA[i]);
        }
        return myTmpMap;
    }
}

这篇关于在静态方法类中的构造方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆