Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2005

Tip: Looking for answers? Try searching our database.

Help to understand 'array of classes' example

Thread view: 
ohaya - 17 Oct 2005 18:39 GMT
Hi,

I'm trying to create/use an array of classes, and I found the following
code snippet using Google Groups:

       ...
       rectangle[ ] array_name = new rectangle[ 100 ]; // or whatever
size
       for ( int n = 0; n < 100; ++n )
       {
           array_name[ n ] = new rectangle( );
       }
       ...
       int i = 99;
       int wide = array_name[i].getwidth( );
       ...

The above snippet was from:

http://groups.google.com/group/comp.lang.java.programmer/msg/1ea4bbde51104914

What I'm trying to understand in the above snippet is the line where the
array is initialized:

rectangle[ ] array_name = new rectangle[ 100 ]; // or whatever size

Before I found that post, I was trying something like:

rectangle [] arrayName;            // declear an array of 'rectangle classes'
.
.
rectangle[0] = new rectangle();        // instantiate rectangle/populate array
rectangle[1] = new rectangle();        // instantiate rectangle/populate array

I did it that way because I don't know the number of classes that I'll
want to have in the array of classes ahead of time.

The code per the snippet from the cited posts works, but my original
code would get a NullPointerException, and I don't understand why.

Can someone explain this?

Also, is it possible to do this in a way that I don't have to allocate a
fixed size array?

Thanks,
Jim
jfbriere@gmail.com - 17 Oct 2005 19:02 GMT
There are three things you should know:

1- Declaring an object does not instanciate it (create it).

When you have:
rectangle [] arrayName;

You declare the object 'arrayName' which is of type rectangle[] (array
of rectangle objects).
This does not instanciate it! Meaning no object have been created yet
in memory.

To instanciate it, you must do:
arrayName = new rectangle[100];

Which create an array of 100 slots, each of which must be a rectangle
object.

2- Creating the array of objects does not create the object elements
that the array will hold.

An array is just an holder of n slots of object to be created next.
By doing:
arrayName = new rectangle[100];
This creates the array (holder) of n slots that will contain rectangle
objects.
For the moment, all the 100 slots have the null value.
Next you do:
arrayName[0] = new rectangle();
arrayName[1] = new rectangle();
arrayName[2] = new rectangle();
...
This create n rectangle objects, and assign each of them to a given
slot of the array.

3- All arrays are fixed length. They are not growable.
You cannot do
arrayName = new rectangle[];
Then later decide how many slots will be created.

So what is the solution of your specific problem?
Don't use arrays.
Use java.util.ArrayList instead.
This is a list object, so it is growable.
In the end, when you have added all the objects needed,
you could allways convert it to an array (with fixed length).

Eg.:

// first we create the list
ArrayList list = new ArrayList();
// then we add all the elements
list.add(new rectangle());
list.add(new rectangle());
list.add(new rectangle());
// in the end, we could convert it to a fixed length array
rectangle[] arrayName = new rectangle[list.size()];
list.toArray(arrayName);
"." - 17 Oct 2005 19:35 GMT
> Hi,
>
[quoted text clipped - 43 lines]
> Thanks,
> Jim

The code:

    rectangle[] r = new rectangle[10];
    for(int i = 0; i < r.length; i++)
        r[i] = new rectangle();

is short for:

    rectangle r0;
    rectangle r1;
    rectangle r2;
    rectangle r3;
    rectangle r4;
    rectangle r5;
    rectangle r6;
    rectangle r7;
    rectangle r8;
    rectangle r9;
    r0 = new rectangle();
    r1 = new rectangle();
    r2 = new rectangle();
    r3 = new rectangle();
    r4 = new rectangle();
    r5 = new rectangle();
    r6 = new rectangle();
    r7 = new rectangle();
    r8 = new rectangle();
    r9 = new rectangle();

The line:

    rectangle[] r = new rectangle[10];

is short hand for declaring 10 variables than reference rectangle objects.

Another way to look at it is:

    rectangle r;
    rectangle[] s;

The variable r is a pointer to a rectangle object. The variable s is a
pointer to an array of rectangle objects. We have not declared an array so
s[0] is meaning less. You have to declare the array that holds the
references. Pictorially (might look bad if you don't have a
non-proportional font):

rectangle r;

     r
   +---+
   |   ---->
   +---+

r = new rectangle();

     r
   +---+    +-----------+
   |   ---->|           |
   +---+    |    new    |
            | rectangle |
            |           |
            +-----------+

rectangle[] s;

     s
   +---+
   |   ---->
   +---+

s = new rectangle[3];

     s
   +---+    +---+
   |   ---->|   ---->
   +---+    +---+
            |   ---->
            +---+
            |   ---->
            +---+

s[0] = new rectangle();

     s
   +---+    +---+                 +-----------+
   |   ---->|   ----------------->|           |
   +---+    +---+                 |    new    |
            |   ---->             | rectangle |
            +---+                 |           |
            |   ---->             +-----------+
            +---+

Hopefully that is more clear.

Signature

Send e-mail to: darrell dot grainger at utoronto dot ca

ohaya - 17 Oct 2005 21:17 GMT
jfbriere and darrell,

Thanks for the clear explanations, especially about the ArrayList!

Jim
Roedy Green - 17 Oct 2005 22:13 GMT
>What I'm trying to understand in the above snippet is the line where the
>array is initialized:

see http://mindprod.com/jgloss/gotchas.html#ARRAY

You have an array of Objects, namely Rectangles, not an array of
Classes.

That would be a Class[]

Finally see http://mindprod.com/jgloss/codingconventions.html
about how to capitalise names.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.