java.util.ArrayList<T>##
-
ArrayList<T>()
构造一个空数组列表。
ArrayList<Employee> staff =new ArrayList<Employee>();
-
ArrayList<T>(int initialCapacity)
用指定容量构造一个空数组列表
参数:initialCapacity 数组列表的最初容量
ArrayList<Employee> staff =new ArrayList<Employee>(100);
-
boolean add(T obj)
在数组列表的尾端添加一个元素。永远返回true。
参数:obj 添加的元素
staff.add(new Employee("Harry Hacker", , , ));
-
int size()
返回存储在数组列表中的当前元素数量。(这个值将小于或等于数组列表的容量。)
staff.size();
//等价于数组staff的staff.length
-
void ensureCapacity(int capacity)
确保数组列表在不重新分配存储空间的情况下就能够保存给定数量的元素。
参数:capacity 需要的存储容量
staff.ensureCapacity(100);
-
void trimToSize()
将数组列表的存储容量削减到当前尺寸。(应该在确认不会添加任何元素时调用)
-
void set(int index, T obj)
设置数组列表指定的元素值,这个操作将覆盖这个位置的原有内容。
参数:index 位置(必须介于0~size()-1之间)
obj 新的值
-
T get(int index)
获得指定位置的元素值。
参数:index 获得的元素位置(必须介于0~size()-1之间)
-
void add(int index, T obj)
向后移动元素,以便插入元素。
参数:index 插入位置(必须介于0~size()-1之间)
obj 新元素
所有位于index之后的元素都要向后移动一个位置。
-
T remove(int index)
删除一个元素,并将后面的元素向前移动。被删除的元素由返回值返回。
参数:index 被删除的元素位置(必须介于0~size()-1之间)
所有位于index之后的元素都要向前移动一个位置。
- 类型化与原始数组列表的兼容性
确保不会造成严重的后果后,可以用@SuppressWarnings("unchecked")标注来标记这个变量可以接受类型转换。
@SuppressWarnings("unchecked") ArrayList<Employee> result = (ArrayList<Employee>) employeeDB.find(query);//yields another warning
package arrayList;
import java.util.*;
import equals.Employee;
/**
* This program demonstrates the ArrayList class
* @author Mr.Ding
*@version 1.8.0 2017-11-04
*/
public class ArrayListTest {
public static void main(String[] args){
//fill the staff array list with three Employee objects
ArrayList<Employee> staff = new ArrayList<>();
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
//raise everyone's salary by 5%
for(Employee e : staff){
e.raiseSalary(5);
}
//print out information about all Employee objects
for(Employee e : staff){
System.out.println("name= " + e.getName() + ",salary= " + e.getSalary() + ",hireDay= " + e.getHireDay());
}
}
}