Java ArrayList的基本方法

388 阅读3分钟

ArrayList是Java里的常用数据结构,与Java原始的Array对象相比,Array最大的优点就是自动扩容,不会因为初始化容量的限制而无法继续新增数据。如果说Array是一串固定车厢数量的火车,那么ArrayList就是可以灵活增加货箱数量的可增长火车。

常见的操作方法如下

1.新建数组列表

  • 方法1:不限定类型的数组列表 元素可以是任意类型 和Python里的list类似
ArrayList arrayList = new ArrayList();//不限定类型的数组列表
  • 方法2:限定数据类型
ArrayList<Integer> arrayList = new ArrayList<Integer>;
//限定元素类型Integer,初始化容量5
  • 方法3:限定初始化长度
ArrayList<Integer> arrayList = new ArrayList<Integer>(8);
//限定元素类型Integer,初始化容量5,不指定时默认10

其中,限定初始化长度的ArrayList可以在超过自身容量(capacity)时自动扩容为原容量的1.5倍
例如:方法3的初始容量为8,当0-7均被占用,又有新增元素进入时,会自动扩容至12(8 x 1.5)。 为什么是1.5倍,不是2倍数,3倍呢,这是因为1.5倍可以合适地满足自然增长规律的新增容量需求,既不会频繁进行扩容操作,也不会造成太多的内存浪费。

我们应该根据业务元素类型选择合适的初始化方式。

2.新增元素

  • 方法1:默认新增,添加数据至ArrayList尾部
arrayList.add(18);
arrayList.add(19);
arrayList.add(20);
//[18, 19, 20]
  • 方法2:指定索引新增:在指定位置i新增元素,i即以后位置上的元素后移
arrayList.add(18);
arrayList.add(19);
arrayList.add(1,888);
arrayList.add(20);
//[18, 888, 19, 20]
  • 方法3:批量添加
ArrayList<Integer> arrayList2 = new ArrayList<>();
List<Integer> ls = List.of(1, 2, 3, 4, 5);
arrayList2.addAll(ls);

3.删除元素

  • 方法1:清空所有元素
arrayList.clear();
  • 方法2:删除指定位置元素 参数类型:Integer

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
形参: index – the index of the element to be removed
返回值: the element that was removed from the list

ArrayList<String> arrayList1 = new ArrayList<String>(5);
arrayList1.add("Jack");
arrayList1.add("Mike");
arrayList1.add("Tom");
arrayList1.remove(1);//删除索引1位置的元素
System.out.println(arrayList1);
//[Jack, Tom]
  • 方法3:删除首个匹配的指定元素 参数类型: Object

Removes the first occurrence of the specified element from this list


ArrayList<String> arrayList1 = new ArrayList<String>(5);
arrayList1.add("Jack");
arrayList1.add("Mike");
arrayList1.add("Tom");
arrayList1.remove("Tom");
System.out.println(arrayList1);
//[Jack, Mike]

由方法1和方法2可知,remove方法按内容删除还是按索引删除的时候是根据输入参数类型而判断的。但是,我们设想,假如一个数组列表 intArrayList 的元素类型是int类型,我们对该数组列表进行删除元素intArrayList.remove(1),这里的1是会被识别为索引还是元素对象呢? 很不幸,这里是会优先识别为索引,因此,对于含有Integer类型的数组列表我们需要Interger类型的参数转为Object类型,如下所示

arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
System.out.println(arrayList);
arrayList.remove(1)
//按索引:[1,3]
arrayList.remove((Object)1)
//按内容:[2,3]