[1899] in java-interest

home help back first fref pref prev next nref lref last post

Re: Q: array initialization.

daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Tue Sep 19 18:12:57 1995

Date: Tue, 19 Sep 1995 11:40:16 -0800 (PDT)
From: Arthur van Hoff <Arthur.Vanhoff@Eng.Sun.COM>
Reply-To: Arthur van Hoff <Arthur.Vanhoff@Eng.Sun.COM>
To: Christophe Meessen <meessen@cppm.in2p3.fr>
Cc: java-interest@java.Eng.Sun.COM



Hi Christphe,

> I wrote the following command
> 
> SortElem v[] = new SortElem[10];
> 
> What is this command supposed to do ?

It creates an array of length 10. Each element will be initialized to null.

> Are SortElem instances created ? 

No.

> If yes 
>    what constructor is called ?
>    how many instances are created ?

It doesn't work that way.

> According to the reference manual (page 6) this is the way an array of
> instances is created.

Yes.

> 
> Here is a small program that didn't do what I expected
> 
> Suppose a class SortElem;
> 
> public class SortElem[
>   public int val;
> ...
> }
> 
> 
> later...
> 
>   static SortElem v[] = new SortElem[3];
> 
>   v[0].val = 2;
>   v[1].val = 5;
>   v[2].val = 8;
> 
>   for( int i = 0; i < v.length; i++ )
>     System.out.println( v[i].val );
> 
> very simple.
> 
> And the result is....
> 
> 8
> 8
> 8
> 
> Not exactly what I would have expected.
> It is as if only one instance is created and all array elements hold a
> reference to that object !

Only the array is created. You will need to create and assign a SortElem
to each position in the array for it to work.

> This is not the same as in C++ where as many instance are created as there
> are elements in the array and for each one of them the default constructor
> (with no argument) is called.

Right, it is not the same as C++. The array contains references to SortElems,
it doesn't contain the SortElems themselves. 

> Bien cordialement,

Goedenmiddag.

Have fun,

	Arthur van Hoff


-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post