當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.util.ArrayList.add()用法及代碼示例


以下是Java中ArrayList的add()方法:

  1. 布爾值add(Object o):此方法將指定的元素附加到此列表的末尾。
    參數:    
    object o: The element to be appended to this list.
    Exception: NA
    // Java code to illustrate add(Object o) 
    import java.io.*; 
    import java.util.ArrayList; 
      
    public class ArrayListDemo { 
    public static void main(String[] args) 
        { 
      
            // create an empty array list with an initial capacity 
            ArrayList<Integer> arrlist = new ArrayList<Integer>(5); 
      
            // use add() method to add elements in the list 
            arrlist.add(15); 
            arrlist.add(20); 
            arrlist.add(25); 
      
            // prints all the elements available in list 
            for (Integer number : arrlist) { 
                System.out.println("Number = " + number); 
            } 
        } 
    }

    輸出:

    Number = 15
    Number = 20
    Number = 25
    
  2. void add(int index,Object元素):此方法將指定的元素E插入此列表中的指定位置。它將當前在該位置的元素(如果有)和任何後續元素向右移動(將向其索引添加一個)。
    參數:
    index : The index at which the specified element is to be inserted.
    element : The element to be inserted.
    
    Exception:
    Throws IndexOutOfBoundsException if the specified
    index is out of range (index  size()).
    // Java code to illustrate 
    // void add(int index, Object element) 
    import java.io.*; 
    import java.util.ArrayList; 
      
    public class ArrayListDemo { 
    public static void main(String[] args) 
        { 
      
            // create an empty array list with an initial capacity 
            ArrayList<Integer> arrlist = new ArrayList<Integer>(5); 
      
            // use add() method to add elements in the list 
            arrlist.add(10); 
            arrlist.add(22); 
            arrlist.add(30); 
            arrlist.add(40); 
      
            // adding element 35 at fourth position 
            arrlist.add(3, 35); 
      
            // let us print all the elements available in list 
            for (Integer number : arrlist) { 
                System.out.println("Number = " + number); 
            } 
        } 
    }

    輸出:


    Number = 10
    Number = 22
    Number = 30
    Number = 35
    Number = 40
    


相關用法


注:本文由純淨天空篩選整理自 Java.util.ArrayList.add() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。