Initialization of fields: constructors vs initializers

I just thought I could do the wrong thing by using initializers to initialize the fields in the constructor instead. Of cause, I want to talk about DPL...
I am 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 thinking about what will be the BDB really when demarshaling the instance of the object, I came to the idea that it re - build the plan of the elements and forget the one I create carefully in the initializer of... In order to avoid the useless object instantiation I have to initialize the field in the constructor as follows:
@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 a real difference between the approaches of the first and the second? Or I just thought the wrong way?...

Hello

Persistent fields cannot currently be final, since I place them by reflection after the construction of the object. So I'm a bit confused. You set the final fields and it works with I somehow get? You read and a paper trail?

The second approach is better, without the final to avoid the redundant design of the hash table.

-mark

Tags: Database

Similar Questions

  • Field initialization in the constructor or the declaration?

    Hello

    Could someone tell me what is the best practice and why?
    public class Course {
         private List<Student> students;
    
         public Course() {
              this.students = new ArrayList<Student>();
         }
    }
    or
    public class Course {
         private List<Student> students = new ArrayList<Student>();
         
         public Course() {
    
         }
    }
    Thanks in advance!

    I would say that if you know at the time of the statement, then initialize it. It seems the clearest and easiest for me, and in this way, if you have more than one it tor, you don't have to repeat the code.

  • How to initialize a field from date to date of today?

    I have a text formatted as a date field.  I would like to come form with the field initially filled to today's date, but be overridable by the user.

    Is there a place for using document level javascript code when you open the document?  Or you can use the default attribute?

    How can I insert decoment-level code in the PDF?

    Remove the function declaration. All you need is the following:

    this.getField("reqDat").value = util.printd ("mm/dd/yyyy", new Date());

  • PPR initialize a field based on another field user input

    My requirement is I have 2 fields in the VO and user enters in the first field employee number and when it has tabs on
    I should fill in the 2nd field dynamically from database using the EMp num is entered.

    I followed the details according to the OFA dev guide (section Cascade of data changes) but unable to achieve.

    Can help you?


    > > > > >
    Cascading data changes
    Updated data values when the user changes the value in a given field, for example, if the user specifies a provider
    value you want to set the default provider site, follow these instructions:
    11.5.10 notes: OA Framework architecture team is always present in the recommended for implementation
    data cascading. You can follow the instructions below to get an idea of how it works, but is not production
    ready for the random sequencing of the game BC4J < attribute > method call means this special focused on the EO
    method for establishing these values is not reliable.
    Step 1: Set up an messageTextInput element to emit an event PPR (see step 1 in the changing properties of user interface
    (See above). When the value data is changed and a PPR event is raised, OA framework sets the selected data on the
    the underlying view object.
    Step 2: Assuming that the purpose underlying the view is based on an entity object, the Poser of entity object associated with
    with RPP source element must implement the logic to call setters on the target object entity
    attributes. For example, in a purchase order header, the setSupplierID() method calls of the SupplierEOImpl
    Entity expert to get the ID of site default provider, that then passes it to the setSupplierSiteID()
    method.

    Hello

    Yap I expected this problem which is y I gave the code with the value 'true' initially,.

    two things I can suggest,
    realize again, then

    1.), false to validation side customer set or false validation server for this contract num field
    Try again with the code in the same handwriting in processRequestMethod

    mtsecBean.setUnvalidated (true); (try this one first)

    in case of problem also try with this one

    mtsecBean.setServerUnvalidated (true)

    or

    2.) hide this contactnum field and create new through customization

    thanx

    Pratap

  • Best practices to declare and initialize the string?

    What is the best practice for the way in which strings are declared in a class?

    Should it be

    private String chBonjour = "";

    or I should have initialization in the constructors?

    The constructor of servlet is usually called only once, when the servlet is first accessed. But then again maybe something happens, google, servlet life cycle if you must know.

    But let's take a step back here. It seems you are trying to put the fields in servlets. Don't, don't. When two users extract URL of the servlet at the same time, the fields are shared between the two shots. If you store something like HTTP settings in the fields, parameters two hits' will get truncated. The hits may eventually see each and other parameter values.

    The best way is not to have fields of servlets. (Except the constant "final static" maybe, sometimes rarely something else). Well the pain of simultaneity go, servlet life cycle concerns go away, builders servlet if go, init() disappears usually.

  • Newbie question - NullPointerException in enterEventDispatcher

    Hello

    I'm new to the Blackberry development and use the 4.6 SDK Eclipse plugin. I used the sample applications as a basis and try to add 3 buttons to my main screen. It's code to the constructor of the main screen

    public MyAppScreen() {        super(DEFAULT_MENU | DEFAULT_CLOSE);        try{            setTitle(new LabelField("My First App", LabelField.ELLIPSIS                 | LabelField.USE_ALL_WIDTH));                       FieldChangeListener listener = new FieldChangeListener() {              public void fieldChanged(Field field, int context) {                    Field buttonField = (Field) field;                  System.out.println("Button pressed: " + buttonField.getIndex());                }           };              HorizontalFieldManager hfm = new HorizontalFieldManager(                    Manager.HORIZONTAL_SCROLL);             ImageButton commBtn = new ImageButton(Field.FOCUSABLE,                  "img/comm_over.png", "img/comm.png");           commBtn.setChangeListener(listener);                        ImageButton accBtn = new ImageButton(Field.FOCUSABLE,                   "img/acts_over.png", "img/acts.png");           accBtn.setChangeListener(listener);                     ImageButton oppBtn = new ImageButton(Field.FOCUSABLE,                   "img/opp_over.png", "img/opp.png");         oppBtn.setChangeListener(listener);             hfm.add(commBtn);           hfm.add(new RichTextField(Field.NON_FOCUSABLE));            hfm.add(accBtn);            hfm.add(new RichTextField(Field.NON_FOCUSABLE));            hfm.add(oppBtn);                add(hfm);       }       catch(Exception e){         e.printStackTrace();        }   }
    

    I call it in my UiApplication class as follows

    public MyApp() {    MyAppScreen homePage = new MyAppScreen();    pushScreen(homePage);}public static void main(String[] args) {   MyApp app = new MyApp();    app.enterEventDispatcher();}
    

    ImageButton is a custom class whose code I made custom buttons sample application subject to change. When I run the application, I get a NullPointerException and stacktrace illustrates the exception in the MyAppScreen paint method.

    Is someone can you please tell me what could be wrong with the application.

    Thank you.

    @mantaker, sorry, it was just a typo. Fix the code.

    Thanks for all the answers. I solved the problem. Had missed on initialization in a constructor.

    I feel really stupid

  • Remove the screen on the menu Manager, click

    Currently I have a screen, the user can bring up the menu and select an option that displays a series of buttons in a fieldmanager.  It works very much like on click menu create and add buttons to the Manager then the screen.  I want to do now is if the user selects an option in the menu to delete the buttons I'd remove the screen Manager.  I'm trying to do the following (taken from another thread)

       private MenuItem _hideGraph = new MenuItem("Hide graph",110,10)
        {
            public void run()
            {
                try{
                    UiApplication.getUiApplication().invokeLater(new Runnable(){
                        public void run()
                        {
                            synchronized(UiApplication.getEventLock()){
                            delete(gridFieldManager);}
                         }
                     });
                }catch(Exception er){
                    System.out.println(er);
                }
            }
        };
    

    A mistake is not printed, but made a mistake.  Is it possible to remove the handler in this way?

    initialize in the constructor of your display manager, for example. Another option would be to return, but I prefer the first one for a better overview.

    in your case:

    declare the handler as a class variable in the class of your screen. initialize it in the constructor. Add and remove it from your menu methods.

    a general Council: instead delete, you can use replace. at least if you use several insertion/removal routines you can lose the correct index quickly, and if you add a field then rewriting half of your code. for this reason I use a NullField who is not active, I add them to the places where I want to dynamically insert managers.

  • How to customize the display of the camera

    Hello everyone.

    I use the camera in my application. I used this code to get the camera displayed in my application:

            /**
         * Instance of {@see javax.microedition.media.Player} used to manage medias.
         */
        private Player player;
    
        /**
         * The video control..
         */
        private VideoControl videoControl;
    
        /**
         * The vertical layout used to display the camera
         */
        private VerticalFieldManager vfm = new VerticalFieldManager(Field.FIELD_VCENTER);
    
        /**
         * Default constructor.
         */
        public ScanScreen()
        {
            super(NO_VERTICAL_SCROLL);
    
            //Initialize the player.
            try
            {
                this.player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
                this.player.realize();
                this.player.prefetch();
                this.videoControl = (VideoControl) this.player.getControl("VideoControl");
    
                if(this.videoControl != null)
                {
                    // Initialize the field where the content of the camera shall be displayed.
                    Field videoField = (Field) this.videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
    
                    // Display the video control.
                    this.videoControl.setDisplayFullScreen(true);
                    this.videoControl.setVisible(true);
    
                    // Start the player.
                    this.player.start();
    
                    // Add the video field to the main screen.
                    if(videoField != null)
                    {
                        this.vfm.add(videoField);
                    }
                    else
                    {
                        LabelField sorry = new LabelField("Sorry, we cannot use camera right now.");
                        this.vfm.add(sorry);
                    }
                }
            }
            catch(Exception e)
            {
            }
                this.add(this.vfm);
        }
    

    The fact is that the camera covers the entire screen; because of the (true) setFullScreen? But if I remove it and use setDisplayPosition and setDisplaySize, nothing is displayed.

    So, how can I do to make the camera photo displayed in a certain part of the screen (for example a centered window of 240 x 320) and display specific buttons at the top of the screen?

    Thanks in advance.

    As a heads-up, the viewfinder does not any third-party display anything on top of it. From my experience (although I may have been something wrong) I couldn't do two sizes in the viewfinder, full screen and the other half of the screen. If you send odd dimensions it simply not display itself, even if it seems that you should be in him passing the legitimate parameters.

  • JPA - ExceptionInInitializerError when creating EntityManager

    EntityFactoryManager (emf) is well received but the emf.createEntityManager error

    Please see my code to the fragment of my project.

    public class Main {
    
        final private static Properties EMAIL_PROPS;
        final private static String EMAIL_FROM;
        
        static {
     EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("tmpCLMSPU");
    //       System.out.println("EMF: "+emf); //OUTPUT: EMF: org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl@ffa7e1
            EntityManager emTemp = emf.createEntityManager();
     TypedQuery<EmailSettings> emailSettings = emTemp.createNamedQuery("EmailSettings.findByName", EmailSettings.class).setMaxResults(1);
            EmailSettings smtp, port, from;
            smtp = emailSettings.setParameter("name", "SMTP").getSingleResult();
            port = emailSettings.setParameter("name", "Port").getSingleResult();
            from = emailSettings.setParameter("name", "EMAILFROM").getSingleResult();
            // Get system properties
            EMAIL_PROPS = System.getProperties();
            // Setup mail server
     EMAIL_PROPS.put("mail.smtp.host", smtp.getValue());
     EMAIL_PROPS.put("mail.smtp.port", port.getValue()); 
            EMAIL_FROM = from.getValue();
     emTemp.close();
            emf.close();
        }
       //Empty Constructor
      public void Main() {
      }
    public static void main(String[] args) {
        new Main();
    }
    

    My project was successfully running but all of a sudden, it showed the following error:-

    Java.lang ExceptionInInitializerError .

    Caused by: javax.persistence. PersistenceException: java.lang. NullPointerException

    to org.eclipse.persistence.internal.jpa. EntityManagerSetupImpl.deploy (EntityManagerSetupImpl.java:766)

    I use Netbeans IDE JAVA for my project. I am very frustrated after a lot of testing on my end to fix this. I tried now but FAILED: -.

    I ran my program again after each next step but always shows error.

    1. I check my database services. It is connected with success. The connection is OK.
    2. Restart the server (SQL Server) database on Server services.
    3. Remove the directories of the users of the configuration of NetBeans.
    4. Restart the server and also, my client computer.
    5. Create a separate project and copy my original sources. I did part of my project again i.e. configuration adding libraries, databases configuration connections & persistence again unit.

    However same database configuration works very well for another project. I found the same problem on the Internet: -.

    http://www.dreamincode.NET/forums/topic/285379-javaxpersistencepersistenceexception-javalangnullpointerexception/

    No suitable solution is given on above link because it is not a NullPointerException. EntityFactoryMnager is extracted successfully.

    Please see attachments: -.

    1. EmailSettings.java: entity
    2. Main.Java: Execution of the main program
    3. Persistence.Xml.txt: File containing the information of persistence
    4. StackTrace.txt: trace the full stack after error shows.

    Any idea to solve this problem?

    Thanks in advance,

    MALIKA

    This problem is SOLVED. In order to the completion of this forum, I give you the solution here: -.

    I have an entity named ShiftDetail in my project that has the rest of the line error codes: -.

    /**
         * SHIFT SLOT TIME ALLOWED AFTER WHICH SHIFT WILL BE APPLICABLE. Time in If
         * any error occurred for getting this value from CLMS S/w then set it's
         * default value as 40 minutes. Minutes
         */
        public static int SHIFT_SLOT; //Field SHIFTATTENDAFTERSLOT from AttendanceSettings table
        static {
            javax.persistence.EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("myDBPU");
            javax.persistence.EntityManager em = emf.createEntityManager();
            try {
                Object minutes = em.createNativeQuery("SELECT AttendanceSettings.Value FROM AttendanceSettings WHERE rtrim(LTRIM(Name))='SHIFTATTENDAFTERSLOT'")
                        .setMaxResults(1).getSingleResult();
                if (minutes != null && minutes instanceof String)
                    SHIFT_SLOT = Integer.parseInt(minutes.toString());
                else
                    SHIFT_SLOT = 40; //Take default Time Slot as 40-minutes
            } catch (Exception ex) {
                SHIFT_SLOT = 40; //Take default Time Slot as 40-minutes
            }
            emf.close();
        }
    

    I do not use a static field within an entity & should not use EntityFactoryManager to initialize this field. I removed above this source file lines by transferring to another class and I found the solution.

    My problem is solved, but can a tell me logical internal behind it to my knowledge.

    Thank you...

    MALIKA

  • Cannot access memory at address 0 x 0 at start of thread for the connection to build...

    Here is my code,

    void AlertListPage::onOnCallClicked()
    {
        thread = new DownLoadThread();
        QThreadPool *pool = new QThreadPool();
        pool->start(thread,0);
    }
    
    class DownLoadThread: public QObject, public QRunnable {
        Q_OBJECT
    public:
        DownLoadThread();
        virtual ~DownLoadThread();
        virtual void run();
    ...
    ...
    }
    
    cpp...
    
    DownLoadThread::DownLoadThread() {
        // TODO Auto-generated constructor stub
    
    }
    
    DownLoadThread::~DownLoadThread() {
        // TODO Auto-generated destructor stub
        sta::out<<"test";
    }
    
    void DownLoadThread::run()
    {
    ...
    ...
    }
    

    I set the breakpoint at the line:

    pool->

    start at (wire, 0);

    and the first line within the Run() method.

    run once OOP-> start and before running, it rises can not access memory at address 0 x 0.

    I do not see where I put the object as null...

    Thank you.

    Do you need a thread pool and QRunnable? You can also use QThread-> http://qt-project.org/doc/qt-4.8/QThread.html

    You initialize QObject in constructor? It's not like so, cause your Builder does not need a QObject as a parent. Then maybe parent is set to NULL.

  • Application with the background thread

    IDE: Blackberry JDE Version 4.5.0.7

    Simulator: About us - Smartphone BlackBerry 2.9.0.52 Simulator

    Model: BlackBerry Curve 8310 smartphone

    Hi all

    I have an application that, after installation on the BlackBerry must be selected in the application menu only once and will run continuously until it is uninstalled from the device. Code looks like this: -.

    public final class app_name extends Application {   private BackGroundThread _thread;
    
       public static void main(String[] args) {        app_name app = new app_name();        app.enterEventDispatcher();    }
    
        public app_name() {        _thread = new BackGroundThread();         _thread.start();    }
    
        private class BackGroundThread extends Thread {
    
             public BackGroundThread() {            /***initialize parameters in constructor*****/        } 
    
             public void run() {             while(true) {             /*****do stuff using parameters*****/             sleep(10000);           }         }     }}
    

    This code works well. Now, I have to add a user interface that allows the user to change some of the parameters that are used in the thread.

    (1) as a first step, I have to change application to UiApplication to allow pushScreen to use. Since it's a subclass, I would have no problem with this law?

    (2) to get the UI goes, my plan was to declare another class (extends screen) within app_name. What is the right way to go?

    (3) parameters must be manipulated such that there is no risk of conflict of data didn't pack the thread class and the class screen try to access settings at the same time. So using the semaphore will be a good strategy?

    (4) any other questions I may be brought to face or is it better to do this quite differently? I wonder if the instance of the thread class will actually be run side-by-side in the user interface and if the user interface to stop smoking will actually affect the Backgorund thread anyway. It might be better to create a completely separate application for the bit of UI that can access this application settings, but I don't know how to do this.

    My apologies for the long post. Any help will be greatly appreciated.

    Hello

    PersistentObject is synchronized, so that it will not conflict data. You can search for "BlackBerry_Application_Developer_Guide_Volume_2" which has the details of the store persistent in the section "persistent data storage.

    Thank you.

  • Approach to singleton for screens

    Hello

    I would like to know if it is advisable to use a singleton pattern when you push the screen on the stack.

    For example:

    package com.xyz.mobile;

    Import net.rim.device.api.ui.container.MainScreen;

    SerializableAttribute public class EntryScreen extends form {}

    Private Shared EntryScreen thisInstance = null;
       
    private EntryScreen() {}
    Super();
    TODO initialize the fields here
    }
       
    public static getInstance() {} EntryScreen
    {if(thisInstance==null)}
    thisInstance = new EntryScreen();
    }
    Return thisInstance;
    }
       
    }

    Now in my application UI I would call:

    pushScreen (EntryScreen.getInstance ());

    The advantage I see is I would not re - initialize my fields whenever I want to push the EntryScreen in the stack. Is this recommended practice. ? Kindly guide me with this.

    Thanking you,

    Kind regards

    S.A.Norton Stanley

    If you have a reference to the screen, it will not change.

    You can do
    YourScreen yourScreen = new YourScreen();
    pushScreen (yourScreen);
    popScreen (yourScreen);
    pushScreen (yourScreen);
    etc.

  • NullPointerException on new screen

    Hello

    I created a menu item custom to launch a new screen. When I try it on the Simulator, I get a null pointer exception.

    The run method of the menu item:

    public Object run(Object context) {
       UiApplication.getUiApplication().pushScreen(new ExtendedMenuGUI());
       return context;
    }
    

    The screen class

    public class ExtendedMenuGUI extends MainScreen {
    
        private MainScreen mainScreen;
        private static RichTextField commentZone;
    
        public ExtendedMenuGUI() {
            // Initialize the fields.
            commentZone = new RichTextField("Entrez vos commentaires ici", RichTextField.NON_FOCUSABLE);
            LabelField title = new LabelField("Validation", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
            mainScreen.setTitle(title);
            mainScreen.add(commentZone);
        }
    }
    

    Anyone know where the problem comes from?

    Thanks a lot for your help.

    T

    you never assigned anything to your

    Screen

    variable

    probably you don't need it at all. simple use 'that' because your class extends screen

      this.setTitle(title); this.add(commentZone);
    
  • Development in ObjectChoiceField


    you create the field with an array of objects.

    your object might look like this:

    public class {Bean

    secret of private; channel

    description of the private channel;

    {public bean (description of the string, string secret)

    This.secret = secret;

    This.Description = Description;

    }

    public String getSecret() {}

    secret return;

    }

    public String toString() {}

    return description;

    }

    }

    now, create an array of Bean objects and initialize your field with her:

    ObjectChoiceField myChc = new ObjectChoiceField ("beans:", beans, 0, ObjectChoiceField.FIELD_LEFT)

  • How to limit the number of letters, a user can type in an EditField?

    I have an EditField on my screen. How can I limit the number of characters that it accepts?

    Use this type of edit field constructor:

    EditField(String label, String initialValue, int maxNumChars, long style)

    Date of arrival:

    http://www.BlackBerry.com/developers/docs/5.0.0api/NET/rim/device/API/UI/component/EditField.html

Maybe you are looking for