Introduction aux méthodes d'affectation de liste add()... et set()

Table des matières

1. Affichage de la méthode 

2. Introduction à la méthode add() 

2.1.add(Eélément)

2.1.1 Code source 

 2.1.2. Exemple de capture d'écran

2.1.3. Digression provoquée par Null 

2.2.add (index int, élément E)

2.2.1.Code source

 2.2.2. Exemple de capture d'écran

2.2.3.add() provoque une exception IndexOutOfBoundsException Introduction

3. Introduction à la méthode addAll()

 3.1.ajouterTout

3.1.1.Code source 

 3.1.2. Exemple de code

 3.1.3. Exécuter une capture d'écran

四、set(int index,E élément) 

4.1. Méthode de remplacement d'élément : set(int index,E element)

4.1.1.Code source 


1. Affichage de la méthode 

         Comme le montre la figure ci-dessus, les méthodes d'insertion de l'interface de liste de tableaux linéaires en Java sont grossièrement divisées en trois catégories, add, addAll et set.

2. Introduction à la méthode add() 

2.1.add(Eélément)

2.1.1 Code source 

    /**
     * Appends the specified element to the end of this list (optional
     * operation).
     * 将指定的元素追加到此list的末尾(可选操作)
     *
     * <p>Lists that support this operation may place limitations on what
     * elements may be added to this list.  
     * <p>支持此操作的列表可能会限制元素可以被添加到该list中。
     *
     * In particular, some lists will refuse to add null elements, and others will         
     * impose restrictions on the type of elements that may be added.  
     * 特别是一些list将拒绝添加null元素,其他列表将强制对可以添加的元素类型的限制。
     * 
     * List classes should clearly specify in their documentation any restrictions
     * on what elements may be added.
     * List类应该在其文档中明确规定任何限制关于可以添加哪些元素。
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     * @throws UnsupportedOperationException if the <tt>add</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this list
     */

    boolean add(E e);

         En termes simples, cette méthode comporte trois éléments : ajouter de nouveaux éléments à la fin de la liste, transmettre uniquement les éléments d'un type spécifié et une partie de la liste refuse d'ajouter null.

        Mais pour autant que je sache, il ne devrait pas y avoir de « jugement NULL » natif dans le JDK pour rejeter l’ajout de null.

 2.1.2. Exemple de capture d'écran

2.1.3. Digression provoquée par Null 

        La spécification Collection indique qu'une NullPointerException doit être levée lorsque la collection ne prend pas en charge null. Poke》》》Cookie Tutorial Interface Collection<E>   Cependant, cette opération n'est pas nécessaire, c'est donc à vous de choisir.

2.2.add (index int, élément E)

2.2.1.Code source

    /**
     * Inserts the specified element at the specified position in this list
     * (optional operation).  
     * 在此列表中的指定位置插入指定的元素(可选操作)。
     * 
     * Shifts the element currently at that position (if any) and any subsequent 
     * elements to the right (adds one to their indices).
     * 将当前位于该位置的元素(如果有)和任何后续元素向右移动(在其索引中添加一个)。
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws UnsupportedOperationException if the <tt>add</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and
     *         this list does not permit null elements
     * @throws IllegalArgumentException if some property of the specified
     *         element prevents it from being added to this list
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index &lt; 0 || index &gt; size()</tt>)
     */

    void add(int index, E element);

 2.2.2. Exemple de capture d'écran

  

         Lorsque ① est exécuté, l'élément A avec l'indice 1 déplace les éléments 2, 3, 4 et 5 vers l'arrière dans la liste d'origine.

        Lorsque ② et ③ sont exécutés, l'élément B est nouvellement ajouté, mais une IndexOutOfBoundsException (exception hors limites de l'indice) se produit. On peut voir de là que lors de l'utilisation de add(int index, E element), l'une des deux conditions doit être satisfait : un élément existe déjà à l'indice actuel, ou un élément existe à la position précédente de l'indice actuel.

        == "Lorsqu'il n'y a aucun élément dans la liste, l'indice d'ajout doit commencer à 0, sinon le problème de l'indice hors limites se produira également.

2.2.3.add() provoque une exception IndexOutOfBoundsException Introduction

         Être ajouté...

3. Introduction à la méthode addAll()

 3.1.ajouterTout

3.1.1.Code source 

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * collection's iterator (optional operation).  
     * 按照指定集合的迭代器返回的顺序,将指定集合中的所有元素追加到此列表的末尾(可选操作)。
     *
     * The behavior of this operation is undefined if the specified collection is         
     * modified while the operation is in progress.  (Note that this will occur if the
     * specified collection is this list, and it's nonempty.)
     * 如果在操作进行期间修改了指定的集合,则此操作的行为是未定义的。
     * (请注意,如果指定的集合就是这个list,它不是空的。)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of an element of the specified
     *         collection prevents it from being added to this list
     * @throws NullPointerException if the specified collection contains one
     *         or more null elements and this list does not permit null
     *         elements, or if the specified collection is null
     * @throws IllegalArgumentException if some property of an element of the
     *         specified collection prevents it from being added to this list
     * @see #add(Object)
     */

    boolean addAll(Collection<? extends E> c);

        Il ressort du code source ci-dessus que les deux méthodes de addAll sont à peu près les mêmes que l'utilisation de add, qui sont toutes deux ajoutées dans la liste d'origine ou ajoutées à la position spécifiée de la liste d'origine, et la plage de valeurs de l'indice ne peut pas se rencontrer (index < 0 || index > size()), mais

        1. Add ajoute des éléments et addAll ajoute Collection<? extends E> c

        2. Lorsque add est utilisé, null n'est pas autorisé dans certaines listes, mais des éléments null peuvent toujours être ajoutés à la liste ;

              addAll ne permet pas d'ajouter des valeurs nulles, mais peut ajouter des éléments nuls

 3.1.2. Exemple de code

package com.task.test;

import java.util.ArrayList;
import java.util.List;

public class T1 {

    public static void main(String[] args) {

        List<String> list1 = new ArrayList<>();
        new T1().returnList1(list1);

        List<String> list2 = new ArrayList<>();
        new T1().returnList2(list2);

        List<String> list3 = new ArrayList<>();
        new T1().returnList3(list3);

        List<String> list4 = new ArrayList<>();

        List<String> list5 = null;


        List<String> listAll = new ArrayList<>();
        listAll.addAll(list1);
        System.out.println("1:listAll = " + listAll);
        listAll.addAll(list2);
        System.out.println("2:listAll = " + listAll);
        listAll.addAll(5,list3);
        System.out.println("3:listAll = " + listAll);
        listAll.addAll(list4);
        System.out.println("4:listAll = " + listAll);
        listAll.addAll(list5);
        System.out.println("5:listAll = " + listAll);
    }

    public void returnList1(List list){
        list.add("A1");
        list.add("B1");
        list.add("C1");
        list.add("D1");
        list.add("E1");
        list.add("F1");
        list.add("G1");
    }
    public void returnList2(List list){
        list.add("A2");
        list.add("B2");
        list.add("C2");
        list.add("D2");
        list.add("E2");
        list.add("F2");
        list.add("G2");
    }

    public void returnList3(List list){
        list.add(null);
    }
}

 3.1.3. Exécuter une capture d'écran

         Pour la différence entre list4 et list5, vous pouvez consulter """ Conseils d'initialisation d'ArrayList

四、set(int index,E élément) 

4.1. Méthode de remplacement d'élément : set(int index,E element)

4.1.1.Code source 

    /**
     * Replaces the element at the specified position in this list with the
     * specified element (optional operation).
     * 将此列表中指定位置的元素替换为指定的元素(可选操作)。
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws UnsupportedOperationException if the <tt>set</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and
     *         this list does not permit null elements
     * @throws IllegalArgumentException if some property of the specified
     *         element prevents it from being added to this list
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (index < 0 || index >= size())
     */

    E set(int index, E element);

        1. Il s'agit d'une méthode de remplacement d'élément.

        2. La plage de valeurs de l'indice d'indice lors de l'utilisation de set ne peut pas être comprise entre (index < 0 || index >= size()).

Je suppose que tu aimes

Origine blog.csdn.net/weixin_52255395/article/details/131326485
conseillé
Classement