开发者

NullPointerException while using Array of objects in java

开发者 https://www.devze.com 2023-03-03 14:02 出处:网络
I have this piece of code which is throwing a Null Pointer exception at the commented line.. I think that it may be because I haven\'t initialized the array ParentInterfaces am I right??...the problem

I have this piece of code which is throwing a Null Pointer exception at the commented line.. I think that it may be because I haven't initialized the array ParentInterfaces am I right??...the problem is since this array may contain a number of elements ranging from 2 to 30 I would not like the idea of initializing it in constructor second if I do that woudn't it result in a memory leak in function2 as I have an object there whose reference I am passing to another function????...Is there any other alternative available???

public class Class {
    public String modifier;
    public String name;
    public  Class parent;
    public  Interface[] parentInterfaces;
    public Method[] memberFunctions;
    public Class[] nestedClasses;
    public Interface[] nestedInterfaces;
    public Field[] memberData;
    public int methodCount, classCount, interfaceCount, fieldCount, parentInterfaceCount;

public Class (String classModifier,String className)
{
    modifier=classModifier;
    name=className;
    methodCount=0;
    classCount=0;
    interfaceCount=0;
    fieldCount=0;
    parentInterfaceCount=0;     
}

public void setParentInterfaces (Interface[] interfaces)
{
    while (interfaces[parentInterfaceCount] != null)
    {
// This is the line which throws the NPE
        parentInterfaces [parentInterfaceCount] = interfaces [parentInterfaceCount]; 

parentINterfaceCount++; } } Now the piece of code which results in a call to this function is: (It belongs to a diff function in a diff class)

    // Prev Code    
    else if (child.getNodeName()=="ParentInterface")
    {
        Iflag=1;
        //Element ele=(Element)child;
        JOptionPane.showMessageDialog (null, "Parent Interface found" + child.getTextContent () + "for " + classes[i].name);
        parentInterfaces[parentICount] = new dataObjects.Interface (child.getTextContent ());
        // classes[i].parentInterfaces[parentICount] = new dataObjects开发者_如何学编程.Interface (child.getTextContent ());
        parentICount++;
    }
}
classes[i].setParentInterfaces (parentInterfaces);


Yes, this is because you haven't initialised parentInterfaces.

Your options include:

  1. initialising the array with the maximum size expected (30).
  2. using a resizable Collection (such as ArrayList), which will require some restructuring of your current code, I think.
  3. Using System.arraycopy to copy the interfaces array into the parentInterfaces array

Incidentally, your setParentInterfaces() method won't work, as the array index isn't being incremented.


You declare the parentInterfaces variable but don't initialize it. Try this ....

public void setParentInterfaces(Interface[] interfaces)
{
    parentInterfaces = new Interface[interfaces.length]
    while(interfaces[parentInterfaceCount]!=null)
    {
        parentInterfaces[parentInterfaceCount]=interfaces[parentInterfaceCount]

    }

}


Consider using an ArrayList<Interface> instead of an array, then add items with parentInterfaces.add(item) and retrieve them with parentInterfaces.get(). ArrayLists take care of memory allocation for you.

In fact, it might be better to use ArrayLists instead of arrays for all of your variables.


You should generally initialize arrays before using them. Also, don't name your class Class. That already exists in the java.lang package.


You have not initialized your array. You need to do something like this

parentInterfaces = new Interface[];

Although I must say its a funny code. You do not need to maintain arraycounts in variables in java. you can just say arrayObject.length();

I say pick up a good java book :)


the problem is since this array may contain a number of elements ranging from 2 to 30 I would not like the idea of initializing it in constructor second if I do that woudn't it result in a memory leak in function2 as I have an object there whose reference I am passing to another function????

Simple answer: No. Initializing an array does not create any objects, just an array of null pointers. Even if it did, Java makes worrying about memory "leaks" a bad idea. On theother hand, it can be worth it to worry about memory usage. Since it is a garbage collected language the thing to ask is: can the garbage collector keep my memory footprint small? The primary rule to garbage collector utilization is: dont keep extra pointers to stuff around on the heap. Having pointers set to null on the heap is almost always okay from a memory standpoint. Pointers on the stack are also almost always okay.

On your code:

Your code is hard to read because 1. It is totally not clear what is supposed to do (is this part of a compiler?) 2. Your naming scheme uses keywords in the language/names of the classes used in reflection 3. You have a fair bit of code here, generally it is best to fork tour code and start simplifying it until the absolutely most minimal code that produces your error.

In particular, I dont know what this piece of code is supposed to do:

    while(interfaces[parentInterfaceCount]!=null)
    {
        parentInterfaces[parentInterfaceCount]=interfaces[parentInterfaceCount];

    }

Because you dont increment parentInterfaceCount, this code will either do nothing, or will enter an infinite loop. So, it is very hard for me to figure out what you want. The reason you are getting a null pointer exception is that parentInterfaces[parentInterfaceCount] could only be addressed if parentInterfaces is initialized.

It would be easier to help if I knew what you wanted to accomplish.

That said I think you have two options: either initialize the array to the maximum size expected or use the length of the array being passed to you to compute a size to initialize to at runtime.

Some ideas to make life simpler:

  1. Use a built in array copy method like System.arraycopy
  2. Use a for loop--it makes handling things like incrementing a pointer much easier
  3. Use a collection class
0

精彩评论

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