ArrayList特点
Java中的ArrayList类是一个可以动态增长和缩减的数组,它属于Java集合框架的一部分。具体来说,以下是ArrayList的一些特点:
- 动态大小:与传统数组不同,ArrayList没有固定的大小限制,能够根据需要自动增长或缩减其容量。
- 实现List接口:ArrayList继承了AbstractList类并实现了List接口,这意味着它可以拥有List接口定义的所有功能,包括添加、删除、修改和查询元素等操作。
- 泛型支持:作为一种泛型类,ArrayList可以存储任意类型的对象,这提供了很高的灵活性。在声明时可以指定存储元素的类型,例如
ArrayList<String>
用来存储字符串类型的数据。 - 随机访问效率高:由于内部是通过数组实现的,所以ArrayList支持快速随机访问,时间复杂度为O(1),即可以直接通过索引来快速访问元素。
- 线程不安全:ArrayList不是线程安全的,当多个线程并发访问同一个ArrayList实例时,可能会发生竞争条件,因此在实际多线程环境中需要额外的同步措施。
- 排序和查找方法:可以使用java.util.Collections类中的方法对ArrayList进行排序、查找最大最小元素或者打乱列表的顺序等操作。
- 与数组相互转换:可以将数组转换为ArrayList,也可以将ArrayList转换为数组,这为处理集合和数组之间的数据提供了便利。
ArrayList类常用方法
构造方法
方法名 | 说明 |
---|
public ArrayList() | 创建一个空的集合对象 |
ArrayList(Collection<? extends E> c) | 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。 |
ArrayList(int initialCapacity) | 构造一个具有指定初始容量的空列表。 |
常用成员方法
方法名 | 说明 |
---|
public boolean add(要添加的元素) | 将指定的元素追加到此集合的末尾 |
public boolean remove(要删除的元素) | 删除指定元素,返回值表示是否删除成功 |
public E remove(int index) | 删除指定索引处的元素,返回被删除的元素 |
public E set(int index,E element) | 修改指定索引处的元素,返回被修改的元素 |
public E get(int index) | 返回指定索引处的元素 |
public int size() | 返回集合中的元素的个数 |
示例
public class ArrayListDemo02 {public static void main(String[] args) {//创建集合ArrayList<String> array = new ArrayList<String>();//添加元素array.add("hello");array.add("world");array.add("java");array.add("hello");array.add("world");array.add("java");public boolean remove(Object o):删除指定的元素,返回删除是否成功System.out.println(array.remove("world"));System.out.println(array.remove("javaee"));public E remove(int index):删除指定索引处的元素,返回被删除的元素System.out.println(array.remove(1));public E set(int index,E element):修改指定索引处的元素,返回被修改的元素System.out.println(array.set(1,"javaee"));public E get(int index):返回指定索引处的元素System.out.println(array.get(0));System.out.println(array.get(1));System.out.println(array.get(2));System.out.println(array.get(3)); //public int size():返回集合中的元素的个数System.out.println(array.size());//输出集合System.out.println("array:" + array);}
}
案例
- 创建一个存储字符串的集合,存储3个字符串元素,使用程序实现在控制台遍历该集合
public class Demo3 {public static void main(String[] args) {//1.创建集合对象ArrayList<String> list = new ArrayList<>();//2.添加元素list.add("aaa");list.add("bbb");list.add("ccc");list.add("ddd");//3.遍历System.out.print("[");for (int i = 0; i < list.size(); i++) {//i 依次表示集合里面的每一个索引if(i == list.size() - 1){//最大索引System.out.print(list.get(i));}else{//非最大索引System.out.print(list.get(i) + ", ");}}System.out.print("]");}
}
- 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
public class Demo4 {public static void main(String[] args) {//1.创建集合对象,用来存储数据ArrayList<Student> list = new ArrayList<>();//2.创建学生对象Student s1 = new Student("zhangsan",16);Student s2 = new Student("lisi",15);Student s3 = new Student("wangwu",18);//3.把学生对象添加到集合中list.add(s1);list.add(s2);list.add(s3);//4.遍历for (int i = 0; i < list.size(); i++) {//i 依次表示集合中的每一个索引Student stu = list.get(i);System.out.println(stu.getName() + ", " + stu.getAge());}}
}