[1886] in java-interest

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

Q: array initialization.

daemon@ATHENA.MIT.EDU (Christophe Meessen)
Tue Sep 19 15:39:28 1995

Date: Tue, 19 Sep 1995 18:32:56 +0200
To: java-interest@java.Eng.Sun.COM
From: meessen@cppm.in2p3.fr (Christophe Meessen)

hello,

another question.

I wrote the following command

SortElem v[] = new SortElem[10];

What is this command supposed to do ?
Are SortElem instances created ? 
If yes 
   what constructor is called ?
   how many instances are created ?
According to the reference manual (page 6) this is the way an array of
instances is created.

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 !

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.

Bien cordialement,

Ch.Meessen

-
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