Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to implement array of objects???

 
doug byrnes
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to work with an array of objects but I can't get it to work! Can anyone tell me how come this code gives a Null Pointer error:
class bar
{
bar() { }
private int x, y;
public void setcoords(int inx, int iny) {this.x = inx; this.y = iny;}
}
class foo
{
private static bar[] mybar = new bar[100];
public static void main(String[] args)
{
mybar[2].setcoords(2,2); // GIVES NULL POINTER ERROR
}
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java "Bar aBar;" declares a reference to an object that must be an instance of Bar. (This is different than in C++.) To create a Bar object and have aBar refer to it, you must do something like "aBar = new Bar();".
The same applies to arrays. Each element of an "array of objects" really holds a reference to such an object. But it is a null reference until you create such an object and assign it to the array element. So try somethink like:
public static void main(String[] args)
{
for (int i=0; i < mybar.length; ++i) mybar[i] = new bar();
mybar[2].setcoords(2,2); // no longer GIVES NULL POINTER ERROR
}
Not that this situation is different for primative types, like int or float.
 
Michael Hildner
Ranch Hand
Posts: 297
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although you have declared an array of bars, you have not initialized any of them, so they're all null.
You could initialize them with someting similar to:
 
doug byrnes
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic