1

Probably this would be the very most basic question in Java. I want to tell you that i am basically from c background. Please bear with me.

I have a class and would like to have mHTable of type Hasbtable.

Question:

Where do i allocate memory for mHTable ? In the class definition or constructor?. Both seems to be working.

Case 1:

public class SampleClass
{
    Hashtable<Integer, Integer> mHTble = new Hashtable<Integer, Integer>();

}

Or

 public class SampleClass
{
  public SampleClass()
  {
     mHTble = new Hashtable<Integer, Integer>();
   }
}

I am trying this in Android.

DrunkenMaster
  • 1,218
  • 3
  • 14
  • 28
  • 1
    Memory allocation may not be the right expression, Java isn't such a low-level language as C, and you don't allocate memory by yourself. – Arnaud Jan 08 '16 at 08:03
  • 1
    They're identical: [Should I instantiate variables on declaration or in the constructor?](http://stackoverflow.com/questions/1994218/should-i-instantiate-instance-variables-on-declaration-or-in-the-constructor) – PPartisan Jan 08 '16 at 08:05
  • Both are valid. depends on ya logic and usage. – Scary Wombat Jan 08 '16 at 08:06
  • There's hardly any difference. You also could use an instance block { mHTble = new Hashtable(); } Java will always create mHTable on the heap. In fact, objects (unlike in C/C++) are never created on the stack. Btw, a HashTable is legacy code and these days, either a HashMap or ConcurrentHashMap (thread safe) are preferred. – dsp_user Jan 08 '16 at 08:07
  • 1
    This is going too deep, but to correct @dsp_user, the objects *can* be created on stack - look up "escape analysis". But to sum up: it shouldn't matter for most of the cases. :) – pwes Jan 08 '16 at 08:11
  • Yes (thank you pointing that out), but only the Java compiler can make this change (in some cases), so it's really not something the programmer has control over. :) – dsp_user Jan 08 '16 at 08:28

1 Answers1

0

It generally doesn't matter. Use the version you fill comfortable with. If you have many constructors, you might prefer the direct field initialization.

As a guideline, if you don't want to change the reference (i.e. the mHTble variable, not the hashtable entries themselves), make it final; then you don't forget to initialize it (compiler will tell you so) and you save yourself from NullPointerExceptions

public class SampleClass
{
  private final Hashtable<Integer, Integer> mHTble;

  public SampleClass()
  {
     mHTble = new Hashtable<>();
   }
}    
pwes
  • 2,040
  • 21
  • 30