开发者

correct way of initializing variables

ok this is just a shot in the dark but it may be the cause of most of the errors ive gotten.

when your initializing something. lets say a smal swing program. would it go like this

variables here
{
  private Jlist contactList;
  String [] contactArray;
  ArrayList <String> contactArrayList;
  ResultSet namesList


// constructor here

public whatever()
{
    GridLayout aGrid = new GridLayout(2,2,10,10);

    contact1 =  new String();
    contact2 =  new String();
    contact3 =  new String();

    contactArrayList = new ArrayList<String>();

// is something supposed too go in the () of this JList?
   contactList = new JList();

   contactArray = new String[5];

   from1 =new JLabel ("From: " + contactArray[1]);



gridlayout.add(components)// theres too many components to write onto SO.

}


// methods here

public void fillContactsGui()
{
    createConnection();
ArrayList<String> contactsArrayList = new ArrayList<String>();

    while (namesList.next())
    {
        contactArrayList.add(namesList.getString(1));
        ContactArray[1] = namesList[1];
    }
}

i know this is probably a huge beginner question but this is the code ive gotten used too. im initializing thigns three and fours times without meaning too because im not sure where they gp. can anyone shed some light on this?

p.s. sorry for the messy sample code. i done my best.


ok a little clearer here then.

the general layout of code is what im asking about.

my code is formatted like this.

variables; constructor; methods;

would i be right in saying it should look like this

 public class test
{
  int i;

  public test()
  {
    i = 0;
 }

  public void addi()
  {
   i = i +1;
  }
}

and not like this

public class test
{
  int i = 0;

  public test()
  {
   int i = 0;
  }


  public void addi(开发者_运维技巧)
  {
    int i = i +1;
  }
}

im trying to figure out the right way to initialize variables. because im defining them each time i use them


Variables can be initialized in different locations for different reasons. For instance, in your example code, you always initialize your contact list to a new JList. That could be done in the "variables here" section as private JList contactList = new JList().

Your contactArrayList looks like it would normally be based upon parameters passed into the constructor, so the items should be added to it in the constructor. If you were to take this approach, the contactArrayList should be declared final though. That would force all constructors to initialize the list. (If you didn't want to declare it final, you would want to initialize it at declaration time in the same way the contactList was handled.)

Occasionally, a field cannot (or should not) be initialized until after an instance of the class has been constructed. In those cases, you must be very careful in how you access and use the field to ensure that it is not used in an uninitialized state.


You should generally initialize variables as soon as possible—whenever the initial value is known. Instead of

ArrayList<String> contactArrayList;

consider this

static final int INITIAL_LIST_SIZE = 100;
List<String> contactArrayList = new ArrayList<String>(INITIAL_LIST_SIZE);

Here's a list of default values for class variables, instance variables, or array components.

Addendum: It's generally frowned on to duplicate default initializations. In your later example, the default initialization sets i to zero.

Erratum: Note corrected comment regarding int i = 0 in test constructor, which hides field i.

public class test {

    int i = 0; // superfluous, "int i;" is enough 

    public test() {
        int i = 0; // hides field i
    }

    public void addi() {
        int i = i + 1; // hides field i; won't increment field i
    }
}


the only problem with not initialising things is you leave yourself open to null pointer exceptions. ideally you should initialise everything you need in your constructor, so you can be sure that every other method has something to work with. the alternative is to check whether things are null before calling methods on them (eg if (list != null && list.size() > 0))


Many of your questions are answered in this tutorial on Object Initialization in Java.

You'll learn instance variables are initialized to default values based on their type, when to use static initializers, when to use the constructor, initialization with respect to inheritance, etc.

Here are some other worthy resources:

  • Sun's Initialization tutorial
  • Initialization chapter of Java in a Nutshell
  • Mindprod's Initialization page


Your last example -- the one with "public test() { int i=0; }" probably won't work as intended. By redeclaring the variable "int" in test and addi, you now have three variables named "i": the member variable defined at the top, a local variable in test, and another local variable in addi. The member value is not changed by either of the functions.

I would definately avoid initializing variables with dummy values, like your "contact1=new String()". Yes, this prevents you from getting a compile error for uninitialized variables or maybe throwing a null pointer exception. But if you get an error without this, then that must mean that you failed to put a real value into the variable. Setting the dummy value doesn't solve the problem, it just hides it. It's like putting tape over a warning light in your dashboard: Yes, you don't see a warning any more, but that's not because the problem is fixed, it's just because you covered it up.

There are really cases where it makes sense to set a default value and then maybe you'll replace it with some other value and maybe you won't. I'm not saying that's a bad practice. I'm saying that if you get errors for unitialized variables, don't blindly initialize them to something meaningless. Figure out why they don't have a value and fix the real problem.

Beyond that, I'm not sure what to say about your example. I'm not sure what you're trying to accomplish. You have variables named contact1, contact2, and contact3 that don't appear to ever be used. contactArray is apparently supposed to be populated by fillContactsGui, but I don't see where it is ever called. I'm not sure if these are flaws in your logic or if this is just an incomplete example.

As to the general proper way to initialize and use data:

If a variable can be local, make it local. In that case, ideally initialize it at the time you declare it. Like:

public void foobar()
{
  ... do some stuff ...
  int i=0;
  ... do other stuff ...
  i=i+j;
  ... etc ...
}

I'd avoid defining it and then later initializing it if possible, because this creates the possibility that you fail to initialize it. Of course, if it may be initialized in two different ways, this is difficult to avoid. Like:

public void foobar()
{
  int i;
  if (plugh>0)
    i=plugh;
  ... bunch more logic ...
  // Inside some IF so we won't even get here if i was set earlier
  if (zork==true)
    i=shambar;
  ... etc ...
}

Still, the more you can keep it together, the better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜