一、概念
ArrayList是一个集合容器类,创建一个对象之后就可以往容器中添加内容。
按照度娘的解释:ArrayList就是动态数组,用MSDN中的说法,就是Array的复杂版本,它提供了动态的增加和减少元素,实现了ICollection和IList接口,灵活的设置数组的大小等好处。
二、构造方法
ArrayList() 构造一个初始容量为 10 的空列表。
ArrayList(int initialCapacity) 构造一个具有指定初始容量的空列表,当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。
ArrayList(Collection<? extends E> collection) 创建一个包含collection的ArrayList
三、API
boolean add(E object)
boolean addAll(Collection<? extends E> collection)
void clear()
boolean contains(Object object)
boolean containsAll(Collection<?> collection)
boolean equals(Object object)
int hashCode()
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object object)
boolean removeAll(Collection<?> collection)
boolean retainAll(Collection<?> collection)
int size()
<T> T[] toArray(T[] array)
Object[] toArray()
四、遍历ArrayList
1.使用for/foreach循环遍历
for循环
public static void function(){
ArrayList<String> al= new ArrayList<>();
al.add("123");
al.add("lllll");
al.add("123");
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
}
foreach循环
public static void function(){
ArrayList<String> al= new ArrayList<>();
al.add("123");
al.add("lllll");
al.add("123");
for (String string : al) {
System.out.println(string);
}
}
2.使用迭代器遍历
public static void function(){
ArrayList<String> al= new ArrayList<>();
al.add("123");
al.add("lllll");
al.add("123");
Iterator<String> it=al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}