这里我们讨论Java.util.ArrayList
类的add()
方法。此方法用于向ArrayList
添加元素。以下是方法签名:
public boolean add(Object element)
例
package beginnersbook.com;
import java.util.ArrayList;
public class Details {
public static void main(String[] args) {
//ArrayList<String> Declaration
ArrayList<String> al= new ArrayList<String>();
//add method for String ArrayList
al.add("Ram");
al.add("Shyam");
al.add("CPS");
al.add("John");
al.add("Steve");
System.out.println("Elements of ArrayList of String Type: "+al);
//ArrayList<Integer> Declaration
ArrayList<Integer> al2 = new ArrayList<Integer>();
//add method for integer ArrayList
al2.add(1);
al2.add(34);
al2.add(99);
al2.add(99);
al2.add(78);
System.out.println("Elements of ArrayList of Integer Type: "+al2);
}
}
输出:
Elements of ArrayList of String Type: [Ram, Shyam, CPS, John, Steve]
Elements of ArrayList of Integer Type: [1, 34, 99, 99, 78]