Skip to Main Content

Berkeley DB Family

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Fields initialization : initializers vs constructors

753675Mar 16 2010 — edited Mar 18 2010
I've just come to thought that I might be doing the wrong thing using initializers instead of initializing fields in the constructor. Of cause I'm speaking of DPL..
I'm used to do something like this:
@Persistent
class Compound
{
   private final Map<Integer, Integer> elements = new HashMap<Integer, Integer>();

   private Compound() {} //dummy private default constructor to be used by BDB

   //actual constructor to be used in the code
   public Compound(int initialValue)
   {
     //some specific initialization...
     //e.g.:
     elements.add(initialValue, initialValue);
   } 
}
But while thinking about what will BDB actually do when demarshaling the object instance, I came to idea that it would re-construct the elements map and forget the one I carefully create in the initializer.. So to avoid the useless object instantiation I'd have to initialize the field in constructor like this:
@Persistent
class Compound
{
   private final Map<Integer, Integer> elements;

   //dummy private default constructor to be used by BDB
   private Compound()
   {
     //now I have to assign something to elements field because it's final.. 
     // or just remove the *final* modifier???
     elements = null;
   } 

   //actual constructor to be used in the code
   public Compound(int initialValue)
   {
     elements = new HashMap<Integer, Integer>()
     //some specific initialization...
     //e.g.:
     elements.add(initialValue, initialValue);
   } 
}
So my question is: is there any actual difference between the first and second approaches? Or I just thinking the wrong way?..
This post has been answered by Greybird-Oracle on Mar 16 2010
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 15 2010
Added on Mar 16 2010
5 comments
1,909 views