(1) add an element
public boolean add (E element) add an element to the end of the collection
public void add (int index, E element) add an element to the specified index
(2) to obtain elements
public E get (int index) Returns the element at the specified index
(3) remove elements
Example:
1 import java.util.ArrayList; 2 3 public class Demo01 { 4 public static void main(String[] args) { 5 // 创建集合对象 6 ArrayList<String> arrayList=new ArrayList<String>(); 7 8 //添加String类型数据, public boolean add(E element) 9 boolean b1 = arrayList.add("hello"); 10 arrayList.add("world"); 11 arrayList.add("inspur"); 12 13 System.out.println(arrayList); 14 System.out.println(b1); 15 16 //添加String类型数据, public void add(int index, E element) 17 arrayList.add(1,"you"); 18 arrayList.add(1,"we"); 19 20 System.out.println(arrayList); 21 22 //获取数据 public E get(int index) 23 System.out.println(arrayList.get(2)); 24 25 //删除数据 public boolean remove(Object obj) 26 27 boolean b2=arrayList.remove("Hello"); 28 boolean b3=arrayList.remove("hello"); 29 System.out.println("b2:"+b2+" b3:"+b3); 30 System.out.println(arrayList); 31 32 //删除数据 public E remove (int index) 33 String str1=arrayList.remove(0); 34 System.out.println("str1:"+str1); 35 System.out.println(arrayList); 36 37 //修改数据 public E set(int index, E element) 38 39 String str2 = arrayList.set(0,"first"); 40 System.out.println("str2:"+str2); 41 is System.out.println (the arrayList); 42 is 43 is // Get set length 44 is int arraylength = arrayList.size (); 45 System.out.println (arraylength); 46 is 47 } 48 }
The output is:
[hello, world, inspur] true [hello, we, you, world, inspur] you b2:false b3:true [we, you, world, inspur] str1:we [you, world, inspur] str2:you [first, world, inspur] 3
ArrayList collections traversal
(1) for loop iterates (2) foreach traversal
Example:
. 1 public class Demo02 { 2 public static void main (String [] args) { . 3 // Create a set of objects . 4 the ArrayList <String> = the arrayList new new the ArrayList <String> (); . 5 . 6 // add data of type String . 7 arrayList.add ( "Hello" ); . 8 arrayList.add ( "World" ); . 9 arrayList.add ( "Inspur" ); 10 . 11 System.out.println (the arrayList); 12 is 13 is // for loop iterates 14 System.out.println ( "for loop traversal" ); 15 for ( int I = 0; I <arrayList.size (); I ++ ) { 16 of System.out.print (arrayList.get (I) + "\ T " ); . 17 } 18 is System.out.println (); . 19 20 is // foreach traverse 21 is System.out.println (" traversed using foreach " ); 22 is for (String STR: the arrayList) { 23 is the System.out .print (STR + "\ T" ); 24 } 25 } 26 is }
The output is:
[hello, world, inspur]
for loop traversal
hello world inspur
using foreach traverse
hello world inspur