在Java中返回数组

Dew*_*rld 1 java nullpointerexception

当我运行此代码时,

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


class Posting
{
    String title;
}

public class Test
{
    Posting[] dew()
    {
        Posting[] p = new Posting[100];
        for(int i = 0; i <p.length; i++)
        {
            p[i].title  = "this is " + i;
        }
        return p;
    }

    public static void main(String args[])
    {
        Test t = new Test();
        Posting[] out = t.dew();

        for(int i = 0; i < out.length; i ++)
        {
            System.out.println(out[i].title);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误,运行:

Exception in thread "main" java.lang.NullPointerException
    at mistAcademic.javaProject.newsBot.core.Test.dew(Test.java:20)
    at mistAcademic.javaProject.newsBot.core.Test.main(Test.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
Run Code Online (Sandbox Code Playgroud)

你有什么想法吗?

bob*_*mcr 11

您必须在设置字段之前初始化数组元素.

p[i] = new Posting(/* ... */);
// THEN set the fields
p[i].title = /* ... */;
Run Code Online (Sandbox Code Playgroud)


Thi*_*ilo 9

Posting[] p = new Posting[100];
Run Code Online (Sandbox Code Playgroud)

这只会创建数组本身,所有条目都设置为null.

因此,您需要创建实例并将它们放入数组中.

    for( int i = 0; i <p.length ; i++ )
    {
        p[i] = new Posting();    // <=  create instances
        p[i].title  = "this is " + i ;
    }
Run Code Online (Sandbox Code Playgroud)