Returning array in Java
When I run this code,
/*
* 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);
}
}
}
I get this error, run:
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)
Could you have any idea?
You have to initialize the array element before setting fields on it.
p[i] = new Posting(/* ... */);
// THEN set the fields
p[i].title = /* ... */;
Posting[] p = new Posting[100];
This will only create the array itself, all entries are set to null
.
So you need to create the instances and put them into the array as well.
for( int i = 0; i <p.length ; i++ )
{
p[i] = new Posting(); // <= create instances
p[i].title = "this is " + i ;
}
you have to init your postings
Posting[] dew()
{
Posting[] p = new Posting[100];
for( int i = 0; i <p.length ; i++ )
{
p[i] = new Posting();
p[i].title = "this is " + i ;
}
return p ;
}
You need to initialize each object of the array. Add following lines before
p[i] = new Posting();
p[i].title = "this is " + i ; in the for loop.
By doing : Posting[] p = new Posting[100];
will create an array of 100 null objects. p[0], p[1], p[2]..... p[99] = null so when you do :
p[i].title
its actually same as : null.title
and hence you get NullPOinterException.
精彩评论