开发者

Java, nested class: how to access 'higher' level variable

i got an error when i run this code!

   private class ValuesClass {

            List<Float> value;

            public void addv(String _value) {
                    Float f = new Float(_value);
                    this.value.add(f);
            }
    }

This is the error returned

0.83
0.83
Exception in thread "main" jav开发者_开发知识库a.lang.NullPointerException
    at com.gsware.gsmarketanalyzer.StockQuote$ValuesClass.addv(StockQuote.java:216)

I don't know where is the error!


You have to instantiate the list, otherwise value is null:

List<Float> value = new ArrayList<Float>;


try this

private class ValuesClass {

    List<Float> value;

    public void addv(String _value) {
        Float f = new Float(_value);
        if(this.value==null)
              this.value = new ArrayList<Float>();

        this.value.add(f);

    }
}

or

private class ValuesClass {

    List<Float> value = new ArrayList<Float>();

    public void addv(String _value) {
        Float f = new Float(_value);
        this.value.add(f);

    }
}


value was not initialized and is therefore null


The error was this

 List<Float> value;

solved with

List<Float> value = new ArrayList<Float>();


Did you initialize List<Float> value anywhere before calling addv? With the code you've given it is null.

You can initialize it as follows:

List<Float> value = new ArrayList<Float>;

OR

Since addv isn't static you will need to instantiate ValuesClass and thus have the possibility of lazy initializing value:

public ValuesClass(){
    this.value = new ArrayList<Float>;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜