ArrayList类是List接口的实现类,它实现了可变的数组,允许保存所有的元素,包括null,并可以根据索引位置对集合进行快速的随机访问;缺点是向指定的索引位置插入对象或删除对象的速度较慢。
List集合包括List接口以及List接口的所有实现类。List集合中的元素允许重复,各元素的顺序就是对象插入的顺序。类似Java数组,用户可以通过使用索引来访问集合中的元素。
ArrayList类常用方法
List接口继承了Collection接口,因此包含Collection中的所有方法。此外,List接口还定义了两个非常重要的方法。
方法 | 功能描述 |
---|---|
add(E e) | 添加元素 |
remove(Object o) | 将指定对象从该集合中移除 |
isEmpty() | 返回boolean值,用于判断当前集合是否为空 |
iterator() | 返回在此Collection的元素上进行迭代的迭代器。用于遍历集合中的对象 |
size() | 返回int型值,获取该集合中元素的个数 |
get(int index) | 获得指定索引位置的元素 |
set(int index,Object o) | 将集合中指定索引位置的对象修改为指定的对象 |
注意:Iterator的next()方法返回的是Object。
【例1】遍历集合
在项目中创建类Muster,在主方法中实例化集合对象,并向集合中添加元素,最后将集合中的对象以String形式输出。
public class Muster {
public static void main(String[] args) {
Collection<String> list=new ArrayList<>();//实例化集合类对象
//向集合添加数据
list.add("a");
list.add("b");
list.add("c");
Iterator<String> iterator=list.iterator();//创建迭代器
while (iterator.hasNext()) { //判断是否有下一个元素
String string=(String)iterator.next();//获取集合中的元素
System.out.println(string);
}
}
}
运行结果
【例2】 在项目中创建类Gather,在主方法中创建集合对象,通过Math类的random()方法随机获取集合中的某个元素,然后移除数组中索引位置是“2”的元素,最后遍历数组。
public class Gather {
public static void main(String[] args) {
List<String> list=new ArrayList<>();//创建集合对象
//向集合添加数据
list.add("a");
list.add("b");
list.add("c");
int i=(int)(Math.random()*list.size());//获取0~2之间的随机数
System.out.println("随机获取数组中的元素:"+list.get(i));
list.remove(2);//将指定索引位置的元素从集合中移除
System.out.println("将索引是‘2’的元素从数组移除后,数组中的元素是:");
//循环遍历集合
for (int j = 0; j < list.size(); j++) {
System.out.println(list.get(j));
}
}
}
Math类的random()方法可获得一个0.0~1.0之间的随机数
运行结果