1.ArrayList
Construction method |
illustrate |
public ArrayList() | Constructs an empty list with an initial capacity of 10 |
1.1. Adding elements
member method |
illustrate |
public boolean add(E e) | adds the specified element to the end of this list |
public void add(int index, E element) | Adds an element at the specified index, moving the previous element to the right |
Define an ArrayList class and add elements:
1 ArrayList<String> al = new ArrayList<String>(); 2 al.add("hello"); 3 al.add(0, "world"); 4 5 System.out.println(al); // [world, hello]
When specifying an index, the index out of bounds exception: (the specified index does not exist in the collection)
al.add(7, "USA");
System.out.println(al);
1.2. Delete, modify, check
Types of |
member method |
illustrate |
check | public E get(int index) | Returns the element at the specified position in the list (risk of index out of bounds) |
check | public int size() | Returns the number of elements in the collection |
check | public int indexOf(Object o) | Returns the index of the first occurrence of the specified element in the list collection (does not return -1) |
check | public boolean isEmpty() | no element, returns true |
delete | public E remove(int index) | Deletes the element at the specified position; the return value is the deleted element |
delete | public boolean remove(Object o) | removes the first occurrence of the element; returns true for the containing element |
change | public E set(int index, E element) | Replaces the contents of the specified index with the element; returns the replaced old element |
1.3. Traverse the collection ArrayList
Traversal through the size and get methods of the ArrlyList collection
1 //Sony 2 //said 3 //hello 4 //JavaEE 5 for (int i = 0; i < al.size(); i++) { 6 System.out.println(al.get(i)); 7 } 8 System.out.println(al); //[Sony, said, hello, JavaEE, .]