• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array of objects problem (java 1.4)  RSS feed

 
Alan Smithee
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the class:

class MyClass {
public String pointname;
public Point3D aPoint;
public Edge aEdge;



public MyClass(String pointName, Point3D loc, Edge line) {
vName = pointName;
location = loc;
connection = line;
}

Where:

class Point3D {
public int x , y, z =0;
public Point3D( int X, int Y, int Z ) {
x = X; y = Y; z = Z;
}
}

class Edge {
public int a, b =0;
public Edge( int A, int B ) {
a = A; b = B;
}
}


And the declaration
MyClass[] aClass = new MyClass[22];

Why doesn't the following work? It compiles, but does not execute.

aClass[0].pointname = new String("foo");



.... Thanks in advance.
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where you have created MyClass array?

What do you mean by does not execute?

Naseem
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The statement

MyClass[] aClass = new MyClass[22];

allocates an array containing 22 elements, each of which can refer to a MyClass object, but which is currently null (refers to no MyClass object.) For your code to work, you need to add a loop after this line which creates the 22 MyClass objects and stores them into the array.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We would need to see the code in which these lines appear -- or at least the error message -- but I'm guessing that you have a NullPointerException at the line...

aClass[0].pointname = new String("foo");

When you create the array, you are creating an array that holds 22 references of type MyClass, but you have not created any instances of MyClass. Initially, these array elements are all null references.

The compiler only knows that aClass[0] is a reference of type MyClass. It's not until runtime that the VM discovers there's nothing there.
 
Alan Smithee
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys! That worked great!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!