aspose file tools
The moose likes Beginning Java and the fly likes Array of objects problem (java 1.4) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Array of objects problem (java 1.4)" Watch "Array of objects problem (java 1.4)" New topic
Author

Array of objects problem (java 1.4)

Alan Smithee
Greenhorn

Joined: Mar 21, 2006
Posts: 23
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

Joined: Apr 25, 2005
Posts: 809
Where you have created MyClass array?

What do you mean by does not execute?

Naseem


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

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.


[Jess in Action][AskingGoodQuestions]
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Alan Smithee
Greenhorn

Joined: Mar 21, 2006
Posts: 23
Thanks guys! That worked great!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array of objects problem (java 1.4)
 
Similar Threads
about ==
Using a multidimensional array
Chapter 5 K&B -Doubt
the question ==
Mouse listener question