t
t
t
t
t t 4) Initialisation & nettoyage
tttt
4) Initialization & Cleanup
Texte original t Traducteur : F. DEFAIX et Y. CHICHA
t
t
///
Ce chapitre contient 6 pages
1 2 3 4 5 6
\\\
t t t
t t t
t
t t t
You can see that the instance initialization clause: t On peut voir que la clause d'initialisation d'instance :
t t t
  {
    c1 = new Mug(1);
    c2 = new Mug(2);
    System.out.println("c1 & c2 initialized");
}
t
{
    c1 = new Mug(1);
    c2 = new Mug(2);
    System.out.println("c1 & c2 initialized");
  }
t t t
looks exactly like the static initialization clause except for the missing static keyword. This syntax is necessary to support the initialization of anonymous inner classes (see Chapter 8). t ressemble exactement à la clause d'initialisation statique moins le mot-clé static. Cette syntaxe est nécessaire pour permettre l'initialisation de classes internes anonymes (voir Chapitre 8).
t t t

Array initialization

t

Initialisation des tableaux

t t t
Initializing arrays in C is error-prone and tedious. C++ uses aggregate initialization to make it much safer[31]. Java has no “aggregates” like C++, since everything is an object in Java. It does have arrays, and these are supported with array initialization. t L'initialisation des tableaux en C est laborieuse et source d'erreurs. C++ utilise l'initialisation d'aggregats pour rendre cette opération plus sûre [31]. Java n'a pas d'« aggregats » comme C++, puisque tout est objet en Java. Java possède pourtant des tableaux avec initialisation.
t t t
An array is simply a sequence of either objects or primitives, all the same type and packaged together under one identifier name. Arrays are defined and used with the square-brackets indexing operator [ ]. To define an array you simply follow your type name with empty square brackets: t Un tableau est simplement une suite d'objets ou de types de base, tous du même type et réunis ensemble sous un même nom. Les tableaux sont définis et utilisés avec l'opérateur d'indexation [ ] (crochets ouvrant et fermant). Pour définir un tableau il suffit d'ajouter des crochets vides après le nom du type :
t t t
int[] a1;
t
int[] a1;
t t t
You can also put the square brackets
after the identifier to produce exactly the same meaning:

t Les crochets peuvent également être placé après le nom de la variable :
t t t
int a1[];
t
int a1[];
t t t
This conforms to expectations from C and
C++ programmers. The former style, however, is probably a more sensible syntax,
since it says that the type is “an int array.” That style
will be used in this book.
t Cela correspond aux attentes des programmeurs C et C++. Toutefois, la première syntaxe est probablement plus sensée car elle annonce le type comme un « tableau de int. » Ce livre utilise cette syntaxe.
t t t
The compiler doesn’t allow you to
tell it how big the array is. This brings us back to that issue of
“references.” All that you have at this point is a reference to an
array, and there’s been no space allocated for the array. To create
storage for the array you must write an initialization expression. For arrays,
initialization can appear anywhere in your code, but you can also use a special
kind of initialization expression that must occur at the point where the array
is created. This special initialization is a set of values surrounded by curly
braces. The storage allocation (the equivalent of using new) is taken
care of by the compiler in this case. For example:

t Le compilateur ne permet pas de spécifier la taille du tableau à sa définition. Cela nous ramène à ce problème de « référence. » A ce point on ne dispose que d'une référence sur un tableau, et aucune place n'a été allouée pour ce tableau. Pour créer cet espace de stockage pour le tableau, il faut écrire une expression d'initialisation. Pour les tableaux, l'initialisation peut apparaître à tout moment dans le code, mais on peut également utiliser un type spécial d'initialisation qui doit alors apparaître à la déclaration du tableau. Cette initalisation spéciale est un ensemble de valeurs entre accolades. L'allocation de l'espace de stockage pour le tableau (l'équivalent de new) est prise en charge par le compilateur dans ce cas. Par exemple :
t t t
int[] a1 = { 1, 2, 3, 4, 5 };
t
int[] a1 = { 1, 2, 3, 4, 5 };
t t t
So why would you ever define an array
reference without an array?

t Mais pourquoi voudrait-on définir une référence sur tableau sans tableau ?
t t t
int[] a2;
t
int[] a2;
t t t
Well, it’s possible to assign one
array to another in Java, so you can say:

t Il est possible d'affecter un tableau à un autre en Java, on peut donc écrire :
t t t
a2 = a1;
t
a2 = a1;
t t t
What you’re really doing is copying
a reference, as demonstrated here:

t Cette expression effectue en fait une copie de référence, comme le montre la suite :
t t t
//: c04:Arrays.java
// Arrays of primitives.

public class Arrays {
  public static void main(String[] args) {
    int[] a1 = { 1, 2, 3, 4, 5 };
    int[] a2;
    a2 = a1;
    for(int i = 0; i < a2.length; i++)
      a2[i]++;
    for(int i = 0; i < a1.length; i++)
      System.out.println(
        "a1[" + i + "] = " + a1[i]);
  }
} ///:~
t
//: c04:Arrays.java
// Tableau de types primitifs.

public class Arrays {
  public static void main(String[] args) {
    int[] a1 = { 1, 2, 3, 4, 5 };
    int[] a2;
    a2 = a1;
    for(int i = 0; i < a2.length; i++)
      a2[i]++;
    for(int i = 0; i < a1.length; i++)
      System.out.println(
        "a1[" + i + "] = " + a1[i]);
  }
} ///:~
t t t
You can see that a1 is given an initialization value while a2 is not; a2 is assigned later—in this case, to another array. t On peut voir que a1 a une valeur initiale tandis qu' a2 n'en a pas ; a2 prend une valeur plus tard— dans ce cas, vers un autre tableau.
t t t
There’s something new here: all arrays have an intrinsic member (whether they’re arrays of objects or arrays of primitives) that you can query—but not change—to tell you how many elements there are in the array. This member is length. Since arrays in Java, like C and C++, start counting from element zero, the largest element you can index is length - 1. If you go out of bounds, C and C++ quietly accept this and allow you to stomp all over your memory, which is the source of many infamous bugs. However, Java protects you against such problems by causing a run-time error (an exception, the subject of Chapter 10) if you step out of bounds. Of course, checking every array access costs time and code and there’s no way to turn it off, which means that array accesses might be a source of inefficiency in your program if they occur at a critical juncture. For Internet security and programmer productivity, the Java designers thought that this was a worthwhile trade-off. t Maintenant voyons quelque chose de nouveau : tous les tableaux ont un membre intrinsèque (qu'ils soient tableaux d'objets ou de types de base) que l'on peut interroger — mais pas changer — ; il donne le nombre d'éléments dans le tableau. Ce membre s'appelle length (longueur). Comme les tableaux en Java , comme C et C++, commencent à la case zero, le plus grand nombre d'éléments que l'on peut indexer est length - 1. Lorsqu'on dépasse ces bornes, C et C++ acceptent cela tranquillement et la mémoire peut être corrompue ; ceci est la cause de bogues infâmes. Par contre, Java empêche ce genre de problèmes en générant une erreur d'exécution (une exception, le sujet du Chapitre 10) lorsque le programme essaye d'accéder à une valeur en dehors des limites. Bien sûr, vérifier ainsi chaque accès coûte du temps et du code ; comme il n'y a aucun moyen de désactiver ces vérifications, les accès tableaux peuvent être une source de lenteur dans un programme s'ils sont placés à certains points critiques de l'exécution. Les concepteurs de Java ont pensé que cette vitesse légèrement réduite était largement contrebalancée par les aspects de sécurité sur Internet et la meilleure productivité des programmeurs.
t t t
What if you don’t know how many elements you’re going to need in your array while you’re writing the program? You simply use new to create the elements in the array. Here, new works even though it’s creating an array of primitives (new won’t create a nonarray primitive): t Que faire quand on ne sait pas au moment où le programme est écrit, combien d'éléments vont être requis à l'exécution ? Il suffit d'utiliser new pour créer les éléments du tableau. Dans ce cas, new fonctionne même pour la création d'un tableau de types de base (new ne peut pas créer un type de base) :
t t t
//: c04:ArrayNew.java
// Creating arrays with new.
import java.util.*;

public class ArrayNew {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  public static void main(String[] args) {
    int[] a;
    a = new int[pRand(20)];
    System.out.println(
      "length of a = " + a.length);
    for(int i = 0; i < a.length; i++)
      System.out.println(
        "a[" + i + "] = " + a[i]);
  }
} ///:~
t
//: c04:ArrayNew.java
// Créer des tableaux avec new.
import java.util.*;

public class ArrayNew {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  public static void main(String[] args) {
    int[] a;
    a = new int[pRand(20)];
    System.out.println(
      "length of a = " + a.length);
    for(int i = 0; i < a.length; i++)
      System.out.println(
        "a[" + i + "] = " + a[i]);
  }
} ///:~
t t t
Since the size of the array is chosen at random (using the pRand( ) method), it’s clear that array creation is actually happening at run-time. In addition, you’ll see from the output of this program that array elements of primitive types are automatically initialized to “empty” values. (For numerics and char, this is zero, and for boolean, it’s false.) t Comme la taille du tableau est choisie aléatoirement (en utilisant la méthode pRand( )), il est clair que la création du tableau se passe effectivement à l'exécution. De plus, on peut voir en exécutant le programme que les tableaux de types primitifs sont automatiquement initialisés avec des valeurs “vides” (pour les nombres et les char, cette valeur est zéro, pour les boolean, cette valeur est false).
t t t
Of course, the array could also have been defined and initialized in the same statement: t Bien sûr le tableau pourrait aussi avoir été défini et initialisé sur la même ligne :
t t t
int[] a = new int[pRand(20)];
t
int[] a = new int[pRand(20)];
t t t
If you’re dealing with an array of
nonprimitive objects, you must always use new. Here, the reference issue
comes up again because what you create is an array of references. Consider the
wrapper type Integer, which is a class and not a
primitive:

t Lorsque l'on travaille avec un tableau d'objets non primitifs, il faut toujours utiliser new. Encore une fois, le problème des références revient car ce que l'on crée est un tableau de références. Considérons le type englobant Integer, qui est une classe et non un type de base :
t t t
//: c04:ArrayClassObj.java
// Creating an array of nonprimitive objects.
import java.util.*;

public class ArrayClassObj {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  public static void main(String[] args) {
    Integer[] a = new Integer[pRand(20)];
    System.out.println(
      "length of a = " + a.length);
    for(int i = 0; i < a.length; i++) {
      a[i] = new Integer(pRand(500));
      System.out.println(
        "a[" + i + "] = " + a[i]);
    }
  }
} ///:~
t
//: c04:ArrayClassObj.java
// Création d'un tableau d'objets (types de base exclus).
import java.util.*;

public class ArrayClassObj {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  public static void main(String[] args) {
    Integer[] a = new Integer[pRand(20)];
    System.out.println(
      "length of a = " + a.length);
    for(int i = 0; i < a.length; i++) {
      a[i] = new Integer(pRand(500));
      System.out.println(
        "a[" + i + "] = " + a[i]);
    }
  }
} ///:~
t t t
Here, even after new is called to create the array: t Ici, même apès que new ait été appelé pour créer le tableau :
t t t
Integer[] a = new Integer[pRand(20)];
t
Integer[] a = new Integer[pRand(20)];
t t t
it’s only an array of references,
and not until the reference itself is initialized by creating a new
Integer object is the initialization complete:

t c'est uniquement un tableau de références, et l'initialisation n'est pas complète tant que cette référence n'a pas elle-même été initialisée en créeant un nouvel objet Integer :
t t t
a[i] = new Integer(pRand(500));
t
a[i] = new Integer(pRand(500));
t t t
If you forget to create the object,
however, you’ll get an exception at run-time when you try to read the
empty array location.
t Oublier de créer l'objet produira une exception d'exécution dès que l'on accédera à l'emplacement.
t t t
Take a look at the formation of the
String object inside the print statements. You can see that the reference
to the Integer object is automatically converted to produce a String
representing the value inside the object.
t Regardons la formation de l'objet String à l'intérieur de print. On peut voir que la référence vers l'objet Integer est automatiquement convertie pour produire une String représentant la valeur à l'intérieur de l'objet.
t t t
It’s also possible to initialize
arrays of objects using the curly-brace-enclosed list. There are two
forms:

t Il est également possible d'initialiser des tableaux d'objets en utilisant la liste délimitée par des accolades. Il y a deux formes :
t t t
//: c04:ArrayInit.java
// Array initialization.

public class ArrayInit {
  public static void main(String[] args) {
    Integer[] a = {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };

    Integer[] b = new Integer[] {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };
  }
} ///:~
t
//: c04:ArrayInit.java
// Initialisation de tableaux.

public class ArrayInit {
  public static void main(String[] args) {
    Integer[] a = {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };

    Integer[] b = new Integer[] {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };
  }
} ///:~
t t t
This is useful at times, but it’s more limited since the size of the array is determined at compile-time. The final comma in the list of initializers is optional. (This feature makes for easier maintenance of long lists.) t C'est parfois utile, mais d'un usage plus limité car la taille du tableau est déterminée à la compilation. La virgule finale dans la liste est optionnelle. (Cette fonctionnalité permet une gestion plus facile des listes longues.)
t t t
The second form of array initialization provides a convenient syntax to create and call methods that can produce the same effect as C’s variable argument lists (known as “varargs” in C). These can include unknown quantity of arguments as well as unknown types. Since all classes are ultimately inherited from the common root class Object (a subject you will learn more about as this book progresses), you can create a method that takes an array of Object and call it like this: t La deuxième forme d'initialisation de tableaux offre une syntaxe pratique pour créer et appeler des méthodes qui permet de donner le même effet que les listes à nombre d'arguments variable de C ( “varargs” en C). Ces dernières permettent le passage d'un nombre quelconque de paramètres, chacun de type inconnu. Comme toutes les classes héritent d'une classe racine Object (un sujet qui sera couvert en détail tout au long du livre), on peut créer une méthode qui prend un tableau d'Object et l'appeler ainsi :
t t t
//: c04:VarArgs.java
// Using the array syntax to create
// variable argument lists.

class A { int i; }

public class VarArgs {
  static void f(Object[] x) {
    for(int i = 0; i < x.length; i++)
      System.out.println(x[i]);
  }
  public static void main(String[] args) {
    f(new Object[] {
        new Integer(47), new VarArgs(),
        new Float(3.14), new Double(11.11) });
    f(new Object[] {"one", "two", "three" });
    f(new Object[] {new A(), new A(), new A()});
  }
} ///:~
t
//: c04:VarArgs.java
// Utilisation de la syntaxe des tableaux pour créer
// des listes à nombre d'argument variable.

class A { int i; }

public class VarArgs {
  static void f(Object[] x) {
    for(int i = 0; i < x.length; i++)
      System.out.println(x[i]);
  }
  public static void main(String[] args) {
    f(new Object[] {
        new Integer(47), new VarArgs(),
        new Float(3.14), new Double(11.11) });
    f(new Object[] {"one", "two", "three" });
    f(new Object[] {new A(), new A(), new A()});
  }
} ///:~
t t t
At this point, there’s not much you can do with these unknown objects, and this program uses the automatic String conversion to do something useful with each Object. In Chapter 12, which covers run-time type identification (RTTI), you’ll learn how to discover the exact type of such objects so that you can do something more interesting with them. t A ce niveau, il n'y a pas grand chose que l'on peut faire avec ces objets inconnus, et ce programme utilise la conversion automatique vers String afin de faire quelque chose d'utile avec chacun de ces Objects. Au chapitre 12, qui explique l'identification dynamique de types (RTTI), nous verrons comment découvrir le type exact de tels objets afin de les utiliser à des fins plus intéressantes.
t t t

Multidimensional arrays

t

Tableaux multidimensionels

t t t
Java allows you to easily create multidimensional arrays: t Java permet de créer facilement des tableaux multidimensionnels :
t t t
//: c04:MultiDimArray.java
// Creating multidimensional arrays.
import java.util.*;

public class MultiDimArray {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  static void prt(String s) {
    System.out.println(s);
  }
  public static void main(String[] args) {
    int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
    };
    for(int i = 0; i < a1.length; i++)
      for(int j = 0; j < a1[i].length; j++)
        prt("a1[" + i + "][" + j +
            "] = " + a1[i][j]);
    // 3-D array with fixed length:
    int[][][] a2 = new int[2][2][4];
    for(int i = 0; i < a2.length; i++)
      for(int j = 0; j < a2[i].length; j++)
        for(int k = 0; k < a2[i][j].length;
            k++)
          prt("a2[" + i + "][" +
              j + "][" + k +
              "] = " + a2[i][j][k]);
    // 3-D array with varied-length vectors:
    int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
    }
    for(int i = 0; i < a3.length; i++)
      for(int j = 0; j < a3[i].length; j++)
        for(int k = 0; k < a3[i][j].length;
            k++)
          prt("a3[" + i + "][" +
              j + "][" + k +
              "] = " + a3[i][j][k]);
    // Array of nonprimitive objects:
    Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
    };
    for(int i = 0; i < a4.length; i++)
      for(int j = 0; j < a4[i].length; j++)
        prt("a4[" + i + "][" + j +
            "] = " + a4[i][j]);
    Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
    }
    for(int i = 0; i < a5.length; i++)
      for(int j = 0; j < a5[i].length; j++)
        prt("a5[" + i + "][" + j +
            "] = " + a5[i][j]);
  }
} ///:~
t
//: c04:MultiDimArray.java
// Création de tableaux multidimensionnels.
import java.util.*;

public class MultiDimArray {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod + 1;
  }
  static void prt(String s) {
    System.out.println(s);
  }
  public static void main(String[] args) {
    int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
    };
    for(int i = 0; i < a1.length; i++)
      for(int j = 0; j < a1[i].length; j++)
        prt("a1[" + i + "][" + j +
            "] = " + a1[i][j]);
    // tableau 3-D avec taille fixe :
    int[][][] a2 = new int[2][2][4];
    for(int i = 0; i < a2.length; i++)
      for(int j = 0; j < a2[i].length; j++)
        for(int k = 0; k < a2[i][j].length;
            k++)
          prt("a2[" + i + "][" +
              j + "][" + k +
              "] = " + a2[i][j][k]);
    // tableau 3-D avec vecteurs de taille variable :
    int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
    }
    for(int i = 0; i < a3.length; i++)
      for(int j = 0; j < a3[i].length; j++)
        for(int k = 0; k < a3[i][j].length;
            k++)
          prt("a3[" + i + "][" +
              j + "][" + k +
              "] = " + a3[i][j][k]);
    // Tableau d'objets non primitifs :
    Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
    };
    for(int i = 0; i < a4.length; i++)
      for(int j = 0; j < a4[i].length; j++)
        prt("a4[" + i + "][" + j +
            "] = " + a4[i][j]);
    Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
    }
    for(int i = 0; i < a5.length; i++)
      for(int j = 0; j < a5[i].length; j++)
        prt("a5[" + i + "][" + j +
            "] = " + a5[i][j]);
  }
} ///:~
t t t
The code used for printing uses length so that it doesn’t depend on fixed array sizes. t Le code d'affichage utilise length ; de cette façon il ne force pas une taille de tableau fixe.
t t t
The first example shows a multidimensional array of primitives. You delimit each vector in the array with curly braces: t Le premier exemple montre un tableau multidimensionnel de type primitifs. Chaque vecteur du tableau est délimité par des accolades :
t t t
    int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
};
t
int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
    };
t t t
Each set of square brackets moves you into the next level of the array. t Chaque paire de crochets donne accès à la dimension suivante du tableau.
t t t
The second example shows a three-dimensional array allocated with new. Here, the whole array is allocated at once: t Le deuxième exemple montre un tableau à trois dimensions alloué par new. Ici le tableau entier est alloué en une seule fois :
t t t
int[][][] a2 = new int[2][2][4];
t
int[][][] a2 = new int[2][2][4];
t t t
But the third example shows that each
vector in the arrays that make up the matrix can be of any
length:

t Par contre, le troisième exemple montre que les vecteurs dans les tableaux qui forment la matrice peuvent être de longueurs différentes :
t t t
    int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
}
t
int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
    }
t t t
The first new creates an array with a random-length first element and the rest undetermined. The second new inside the for loop fills out the elements but leaves the third index undetermined until you hit the third new. t Le premier new crée un tableau avec un longueur aléatoire pour le premier élément et le reste de longeur indéterminée. Le deuxième new à l'intérieur de la boucle for remplit les éléments mais laisse le troisième index indéterminé jusqu'au troisième new.
t t t
You will see from the output that array values are automatically initialized to zero if you don’t give them an explicit initialization value. t On peut voir à l'exécution que les valeurs des tableaux sont automatiquement initialisées à zéro si on ne leur donne pas explicitement de valeur initiale.
t t t
You can deal with arrays of nonprimitive objects in a similar fashion, which is shown in the fourth example, demonstrating the ability to collect many new expressions with curly braces: t Les tableaux d'objets non primitifs fonctionnent exactement de la même manière, comme le montre le quatrième exemple, qui présente la possibilité d'utiliser new dans les accolades d'initialisation :
t t t
    Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
};
t
Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
    };
t t t
The fifth example shows how an array of nonprimitive objects can be built up piece by piece: t Le cinquième exemple montre comment un tableau d'objets non primitifs peut être construit pièce par pièce :
t t t
    Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
}
t
Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
    }
t t t
The i*j is just to put an interesting value into the Integer. t L'expression i*j est là uniquement pour donner une valeur intéressante à l' Integer.
t t t

Summary

t

Résumé

t t t
This seemingly elaborate mechanism for initialization, the constructor, should give you a strong hint about the critical importance placed on initialization in the language. As Stroustrup was designing C++, one of the first observations he made about productivity in C was that improper initialization of variables causes a significant portion of programming problems. These kinds of bugs are hard to find, and similar issues apply to improper cleanup. Because constructors allow you to guarantee proper initialization and cleanup (the compiler will not allow an object to be created without the proper constructor calls), you get complete control and safety. t Le mécanisme apparemment sophistiqué d'initialisation que l'on appelle constructeur souligne l'importance donnée à l'initialisation dans ce langage. Quand Stroustrup était en train de créer C++, une des premières observations qu'il fit à propos de la productivité en C était qu'une initialisation inappropriée des variables cause de nombreux problèmes de programmation. Ce genre de bogues est difficile à trouver. Des problèmes similaires se retrouvent avec un mauvais nettoyage. Parce que les constructeurs permettent de garantir une initialisation et un nettoyage correct (le compilateur n'autorisera pas la création d'un objet sans un appel valide du constructeur), le programmeur a un contrôle complet en toute sécurité.
t t t
In C++, destruction is quite important because objects created with new must be explicitly destroyed. In Java, the garbage collector automatically releases the memory for all objects, so the equivalent cleanup method in Java isn’t necessary much of the time. In cases where you don’t need destructor-like behavior, Java’s garbage collector greatly simplifies programming, and adds much-needed safety in managing memory. Some garbage collectors can even clean up other resources like graphics and file handles. However, the garbage collector does add a run-time cost, the expense of which is difficult to put into perspective because of the overall slowness of Java interpreters at this writing. As this changes, we’ll be able to discover if the overhead of the garbage collector will preclude the use of Java for certain types of programs. (One of the issues is the unpredictability of the garbage collector.) t En C++, la destruction est importante parce que les objets créés avec new doivent être détruits explicitement .En Java, le ramasse-miettes libère automatiquement la mémoire pour tous les objets, donc la méthode de nettoyage équivalente en Java n'est pratiquement jamais nécessaire. Dans les cas où un comportement du style destructeur n'est pas nécessaire, le ramasse-miettes de Java simplifie grandement la programmation et ajoute une sécurité bien nécessaire à la gestion mémoire. Certains ramasse-miettes peuvent même s'occuper du nettoyage d'autres ressources telles que les graphiques et les fichiers. Cependant, le prix du ramasse-miettes est payé par une augmentation du temps d'exécution, qu'il est toutefois difficile d'évaluer à cause de la lenteur globale des interpréteurs Java au moment de l'écriture de cet ouvrage. Lorsque cela changera, il sera possible de savoir si le coût du ramasse-miettes posera des barrières à l'utilisation de Java pour certains types de programmes (un des problèmes est que le ramasse-miettes est imprévisible).
t t t
Because of the guarantee that all objects will be constructed, there’s actually more to the constructor than what is shown here. In particular, when you create new classes using either composition or inheritance the guarantee of construction also holds, and some additional syntax is necessary to support this. You’ll learn about composition, inheritance, and how they affect constructors in future chapters. t Parce que Java garantit la construction de tous les objets, le constructeur est, en fait, plus conséquent que ce qui est expliqué ici. En particulier, quand on crée de nouvelles classes en utilisant soit la composition, soit l'héritage la garantie de construction est maintenue et une syntaxe supplémentaire est nécessaire. La composition, l'héritage et leurs effets sur les constructeurs sont expliqués un peu plus loin dans cet ouvrage.
t t t
t t t
t t
\\\
///
t t t
t
     
Sommaire Le site de Bruce Eckel