开发者

Casting inner objects in java - unchecked exception

I'm having a problem with inner classes. I build an object (let's say a train) with an inner class representing states (let's say the stops of the train).

I'm trying to run this code:

private void CustomObjectBuilder (String [] origin) {

  final int array_dim = origin.length;

  InnerCustomObject[] tmp_bin = new InnerCustomObject[array_dim];

  for (int ii = 0; ii < array_dim; ii++) {

   String debug = extractData(origin[ii]);


   tmp_bin[ii].setData(debug);



  }




 }

It compiles just just fine but at runtime I get a null object exception.

What am I doing wrong?

Here you can finde the original code:

public class CustomObject {



    InnerCustomObject [] stops;

    public class InnerCustomObject {

        String name, station, schedTime, depTime, schedRail, depRail;

        public void setData (String origin) {

            this.station = origin;
        }

    }
}

Edit: I solve开发者_StackOverflowd by calling

 CustomObject.InnerCustomObject ico = new CustomObject(). new InnerCustomObject(); 

why it needs to be so verbose?


Well, the most immediate thing I notice is you don't populate tmp_bin[] with any objects after you declare it. When you first create an array, all it contains are nulls.

So when you do this in your loop:

tmp_bin[ii].setData(debug);

There is nothing to invoke setData() on, resulting in the exception.

Re edit: you can just do

InnerCustomObject ico = this.new InnerCustomObject();

since you're creating them within your outer CustomObject class's CustomObjectBuilder() instance method.


InnerCustomObject[] tmp_bin = new InnerCustomObject[array_dim];

declares an array of array_dim elements but all are null. Then this

tmp_bin[ii].setData(debug);

won't work.

No problem with inner classes only with an object that is null (=NPE) so you cannot call the method setData().


In your loop you have to create new instance of InnerCustomObject. By new InnerCustomObject[size] you do not create new instances.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜