array of objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Time
    New Member
    • Jan 2010
    • 77

    array of objects

    Hi ppl,
    whenever we write
    Code:
    class object=new class();
    object gets created; assigning values to it is perfectly fine.
    now in case of array objects:
    Code:
    class object[]=new class[3];
    i had assigned values to
    Code:
    object[0]...3
    by
    Code:
    object[0].variable
    ..its syntactically right but giving run-time error of null pointer assignment.
    Whenever we create an object of any class its a reference variable untill memory is assigned to it..
    but we are clearly using new operator and allocating memory to each object in object array.....where am i mistaking?
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    I could be wrong, but if Java is like some of the other OOP languages I worked with, when you do this:
    Code:
    class object[] = new class[3];
    You are actually creating a new array, and allocating the memory space for three pointers, but you are not initializing any of those three new objects.

    You still need to initialize each object in the array before you can use them:
    Code:
    object[0] = new class();
    Or as a loop:
    Code:
    for(int i=0; i<3; i++)
      object[i] = new class();
    I hope that is correct and helps.

    Comment

    • Time
      New Member
      • Jan 2010
      • 77

      #3
      Yeah i agree with you; that they are not initialized; but
      object[0]=new class();
      allocates memory as new is used and not just initialization. .

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        I'm afraid I don't understand your question here.
        but we are clearly using new operator and allocating memory to each object in object array
        That's not quite true. You're just allocation the memory for a pointer. Those pointers are null. You have to initialize each object in the array if you want to use them.

        If that's not what you are asking, please clarify your question.

        Comment

        • pbrockway2
          Recognized Expert New Member
          • Nov 2007
          • 151

          #5
          Originally posted by Time
          Yeah i agree with you; that they are not initialized; but
          "object[0]=new class()"
          allocates memory as new is used and not just initialization. .
          The line of quote you quoted comes from insertAlias and that does create a new (class) object.

          Your code was "class object[]=new class[3];" and what that does is create a new array.

          Think of the array as a box - with little slots in it marked zero to two. Creating a box (an empty one) is one thing. Creating objects to put in the box is quite another.

          Comment

          Working...