In Java, can a final field be initialized from a constructor helper?

安稳与你 提交于 2019-12-03 22:02:41

Method #2 is your best option. The problem is that if you have an assignment in a private method there is nothing preventing other code in the class outside the constructor calling it, which would then create an issue with an attempted second assignment to the final field.

Java has no construct of a separate method that can only be called during construction.

For completeness, we can make a third option, where you assign the map at initialization and then have the helper method fill it:

 private final HashMap<String, String> myMap = new HashMap<String, String();

And then:

 MyConstructor (String someThingNecessary)
 {
    initializeMyMap(someThingNecessary);

    // other initialization stuff unrelated to myMap
 }


 // helper doesn't work since it can't modify a final member
 private void initializeMyMap(String someThingNecessary)
 {

     myMap.clear();
    myMap.put("blah","blahblah");
    // etc...
  }

And if you really want to be confusing you can use an initializer instead of a constructor, but you should not do that, so unless you really need to know, I won't expand on that.

cjerdonek

How about implementing a private constructor that initializes your HashMap, and then have your main constructor(s) call that private constructor?

For example--

// Helper function to initialize final HashMap.
private MyConstructor()
{
    myMap = new HashMap<String,String>();
    myMap.put("blah","blah");
}

MyConstructor (String someThingNecessary)
{
    // Initialize the HashMap.
    this();
    // Other initialization code can follow.
}

You can modify the signature of the private helper constructor as needed (e.g. to provide parameter data or to make the signature distinct from any public constructors).

Option #2 is the most resuable option, because you can share it among all constructors. What we would need here, are collection initializers of c#. :)

(BTW: #3 won't compile)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!