The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Nullifying Those Pointer Exceptions

Posted by Matt Gerrans on December 08, 2001 at 6:27 PM

Oops - I should have used the pre keyword, not code!


> I am coming from a C++ backround but haven't programmed in a few years. I am repeatedly making the same mistake and I think its due to a general error in how I'm trying to solve things. I keep getting nullpointer exception when I try to create an array of class objects. This also happens when I try to use methods from another class. I have read Java in a Nutshell. I'm not sure I can make my problem any clearer right now because I've been staring at it and fiddling with it so long I don't know what is going on anymore. Can anyone point me to a simplest case scenario of object oriented class use in java? Thanks and sorry to just jump in with a general question like this.

Coming from a C++ background, you may be used to doing something like this:


const int itemCount = 10;
MyObject objects[itemCount ];

or:

MyObject *objects = new MyObjects[itemCount ];

in both these cases, you've created an array and 10 of your objects, which are then pointed to by the array.

However, in Java, when you do this:


final static int itemCount = 10;
MyObject [] objects = new MyObject[itemCount];

all you have done is create an array with 10 slots. You have not created any object. This is more like creating an array of pointers (or references) in C++. You still need to put things in the array:

for(int i=0; i < itemCount; i++ )
objects[i] = new MyObject();

You would have the same problem in C++ if you did this:


MyObject * * objects = new MyObject *[itemCount];
objects[0].MyMethod(); // Crash!
delete [] objects;

- mfg




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us