Perry Smith
Java Questions & Answers
Home /
Java Q & A Page 2 /
Java Q & A Archive Main Page
arrays of objects
Thursday, 03-Dec-98 20:16:31
128.230.30.12 writes:
How do I create an array of objects? Let's say that I have defined a class called L. How do
I create an array of L's?
I have tried the following:
L test[] = new L[25];
and this compiles but when I try to use this in a program I get a null pointer exception.
Any help??
Responses
Re: arrays of objects
Friday, 04-Dec-98 11:03:51
148.5.110.65 writes:
All you have done with the line you have given is created the array. You now need to initialize it with your objects by doing something like:
for (int theIndex = 0; theIndex < 25; theIndex++)
{
test[theIndex] = new L();
}
Scott
Scott_M2
Re: arrays of objects
Friday, 08-Jan-99 09:35:59
139.51.221.72 writes:
A Vector object is used to hold a dynamic array of Objects (that is, class Object objects).
To declare a Vector, you can do the following.
// A vector object is a resizable array
// of Objects. The new Vector() constructor
// initializes the Vector with no elements
// You can also initialize it to some
// set number, say 10 elements, with
// new Vector(10)
private Vector yourVector = new Vector();
To add elements to the Vector, use the addElement() method of the Vector.
yourVector.addElement(someObject);
To find the size of the Vector, use the size() method.
yourVector.size();
This returns the number of elements currently in the Vector object.
To access a particular element at a known location, use the elementAt() method.
yourVector.elementAt(i) = newObject;
where i is an integer used for the index.
To assign what you stored in your Vector to a variable that is not of the Object class, you have to use a narrowing reference. By this, I mean that if you assign a bunch of Point objects to your Vector, and then try to assign one of those Vector elements to a seperate Point object, you will get an error without a using a narrowing reference.
Point myPoint = (Point)yourVector.elementAt(i);
the (Point) portion of that statement indicates that you are narrowing the generic Object back to a Point object, and no error will occur.
This is an alternative way for you to work with an array of Objects, and one that is more dynamic than using a simple array. For more info, you can go to java.sun.com and search for Vector - the language specification has all of the methods of the Vector object.
Hope this is not too much more than you asked for.
Trent
Home /
Java Q & A Page 2 /
Java Q & A Archive Main Page