Maison  >  Article  >  Java  >  Comment initialiser la collection ArrayList en Java

Comment initialiser la collection ArrayList en Java

王林
王林avant
2019-11-26 15:13:012610parcourir

Comment initialiser la collection ArrayList en Java

Présentation

ArrayList est une collection non thread-safe basée sur des tableaux dynamiques. Les éléments d'ArrayList peuvent être vides et répétés, et. en même temps il est ordonné (l'ordre de lecture et de stockage est cohérent).

ArrayList hérite de AbstractList et implémente List, RandomAccess (accessible rapidement), Cloneable (peut être cloné), java.io.Serializable (prend en charge la sérialisation)

Plus de liens gratuits recommandations vidéo : vidéo Java

Il existe trois façons d'initialiser ArrayList :

1. Construction sans paramètre, la longueur par défaut. vaut 10, est la méthode d'initialisation la plus couramment utilisée :

/**
  * Constructs an empty list with an initial capacity of ten.
  */
  public ArrayList() {
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  }

À ce stade, nous pouvons voir à partir du code source qu'il ne contient qu'une seule ligne de code : this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA, puis le DEFAULTCAPACITY_EMPTY_ELEMENTDATA défini peut être trouvé dans le code source :

/**
  * Shared empty array instance used for default sized empty instances. We
  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  * first element is added.
  */
 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

Comme vous pouvez le voir dans les commentaires, le code source définit un tableau vide comme taille par défaut et détermine de combien étendre le tableau lorsque le premier élément est ajouté. Ce paragraphe La logique sera expliquée dans la section Ajout d'éléments ensuite.

2. Spécifiez la longueur d'initialisation :

/**
  * Constructs an empty list with the specified initial capacity.
  * @param  initialCapacity  the initial capacity of the list
  * @throws IllegalArgumentException if the specified initial capacity
  *         is negative
  */
  public ArrayList(int initialCapacity) {
     if (initialCapacity > 0) {
         this.elementData = new Object[initialCapacity];
     } else if (initialCapacity == 0) {
         this.elementData = EMPTY_ELEMENTDATA;
     } else {
         throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
     }
  }

3. Utilisez un objet Collection pour construire

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

Article connexe recommandé. tutoriels :Introduction au développement java

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer