本文共 2860 字,大约阅读时间需要 9 分钟。
Syntax:
句法:
public boolean add(T ele); public void add(int indices, T ele);
add() method is available in java.util package.
add()方法在java.util包中可用。
add(T ele) method is used to add the given ele(element) to the last of this Arraylist.
add(T ele)方法用于将给定的ele(element)添加到此Arraylist的最后一个。
add(int indices, T ele) method is used to add the given ele(element) at the given indices in this Arraylist & shift other elements to the right side.
add(int index,T ele)方法用于在此Arraylist中的给定索引处添加给定ele(element)并将其他元素移至右侧。
add(T ele) method does not throw an exception at the time of adding an element.
add(T ele)方法在添加元素时不会引发异常。
add(int indices, T ele) method may throw an exception at the time of adding an element at the given position.
在给定位置添加元素时,add(int index,T ele)方法可能会引发异常。
IndexOutOfBoundsException: This exception may throw when the given parameter indices are not in a range.
IndexOutOfBoundsException :当给定参数索引不在范围内时,可能引发此异常。
These are non-static methods, so it is accessible with class objects & if we try to access these methods with the class name then we will get an error.
这些是非静态方法,因此可以通过类对象进行访问;如果尝试使用类名访问这些方法,则会收到错误消息。
Parameter(s):
参数:
In the first case, add(T ele)
在第一种情况下, add(T ele)
In the second case, add(int indices, T ele)
在第二种情况下, add(int index,T ele)
Return value:
返回值:
In the first case, the return type of the method is boolean, it returns true if the given element is added successfully.
在第一种情况下,方法的返回类型为boolean ,如果成功添加给定元素,则返回true 。
In the second case, the return type of the method is void, it does not return anything.
在第二种情况下,该方法的返回类型为void ,它不返回任何内容。
Example:
例:
// Java program to demonstrate the example // of add() method of ArrayList.import java.util.*;public class AddOfArrayList { public static void main(String[] args) { // Create an ArrayList with initial // capacity of storing elements ArrayList < String > arr_l = new ArrayList < String > (10); // By using add() method is to add // elements in this ArrayList arr_l.add("C"); arr_l.add("C++"); arr_l.add("JAVA"); arr_l.add("DOTNET"); arr_l.add("PHP"); // Display ArrayList System.out.println("arr_l.add(obj) :" + arr_l); // By using add(int,T) method is to add the // elements at the given index in this ArrayList arr_l.add(2, "JSP"); // Display ArrayList System.out.println("arr_l.add(int,obj) : " + arr_l); }}
Output
输出量
arr_l.add(obj) :[C, C++, JAVA, DOTNET, PHP]arr_l.add(int,obj) : [C, C++, JSP, JAVA, DOTNET, PHP]
翻译自:
转载地址:http://wwozd.baihongyu.com/