ArrayList详解(快来看看叭~)

**List 的实现类之一--------ArrayList **

ArrayList 介绍

ArrayList 是一个普通的类,底层是一段连续的空间,还可以动态扩容,是一个动态类型的顺序表。它继承自 AbstractList, 实现了 List 接口,同时实现了 RandomAccessCloneableSerializable 等接口;因此,ArrayList 支持随机访问、复制以及序列化;

ArrayList 使用

ArrayList 的 3 种构造方式

  • 无参构造 ArrayList()
 List<Integer> list1=new ArrayList<>();

:左边写成 List 是因为便于修改,写成如下方式也是可以的;

 ArrayList<Integer> list1=new ArrayList<>();
  • 指定顺序表初始容量构造: ArrayList(int initialCapacity)
 //构造一个具有10个初始容量的 ArrayList
 List<Integer> list2=new ArrayList<>(10); 
  • 利用其他 Collection 构造: ArrayList(Collection<? extends E> c)
List<Integer> list2=new ArrayList<>(10); 
list2.add(1);
List<Integer> list3= new ArrayList<>(list2);
System.out.println(list3);  // [1]

ArrayList 的常见方法

(1) public boolean add(E e): 尾部插入元素 e

 List<String> list=new ArrayList();
       list.add("0000");
       list.add("1111");
     System.out.println(list);  //[0000, 1111]

(2) public void add(int index, E e): 在index 位置插入e

 List<String> list=new ArrayList();
     list.add("0000");
     list.add("1111");
     list.add(0,"5555");
     System.out.println(list); //[5555, 0000, 1111]

(3) public boolean addAll(Collection<? extends E> c):尾部插入 c 中的元素

//将list中的所有元素插入到list1中
    List<String> list=new ArrayList();
    list.add("0000");
    List<String> list1=new ArrayList<>();
    list1.addAll(list);  //[0000]

(4) public int size():获取有效元素的个数

   System.out.println(list.size());

(5) public E remove(int index) :删除 index 位置元素

 List<String> list=new ArrayList();
        list.add("0000");
        list.add("1111");
        list.remove(1);
        System.out.println(list); //[0000]

(6) public boolean remove(E e) :删除指定元素 e

 List<String> list=new ArrayList();
        list.add("0000");
        list.add("1111");
        list.remove("0000");
        System.out.println(list);//[1111]

(7) public boolean contains(E e):是否包含元素 e

 List<String> list=new ArrayList();
     list.add("0000");
     list.add("1111");
     //包含返回true
     System.out.println(list.contains("0000")); 
      //不包含,返回false
    System.out.println(list.contains("9999"));

(8)public E get(int index):获取 index 位置元素

List<String> list=new ArrayList();
      list.add("0000");
      list.add("1111");
   System.out.println(list.get(1)); //1111

(9) public E set(int index, E e):将 index 位置元素设置为 e

List<String> list=new ArrayList();
        list.add("0000");
        list.add("1111");
        list.set(1,"2222");
     System.out.println(list);//[0000, 2222]

(10) public int indexOf(E e):从前往后找,返回第一次 e 出现的下标

List<String> list=new ArrayList();
        list.add("0000");
        list.add("3333");
        list.add(1,"0000");
    System.out.println(list.indexOf("0000"));//0

(11) public int lastIndexOf(E e):从后往前找,返回第一次 e出现的下标

List<String> list=new ArrayList();
        list.add("0000");
        list.add("3333");
        list.add(1,"0000");
     System.out.println(list.lastIndexOf("0000")); // 1

(12) public List<E> subList(int fromIndex, int toIndex):截取 [fromIndex,toIndex) 部分

 List<String> list=new ArrayList();
        list.add("0000");
        list.add("1111");
        list.add("2222");
        list.add("3333");
        list.add("4444");
  System.out.println(list.subList(1,4));//[1111, 2222, 3333]

(13) public boolean isEmpty():判定链表是否为空

 System.out.println(list.isEmpty());

(14) public void clear():清空

 list.clear();
System.out.println(list.size()); //0

ArrayList 的遍历

三种方式

方式1: for循环+下标

方式2: foreach

方式3 :利用迭代器遍历

具体过程如下

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

//ArrayList 遍历
public class AccessArrayList {
    public static void main(String[] args) {
        List<String>list =new ArrayList<>();
          list.add("0000");
          list.add("1111");
          list.add("3333");
         list.add("4444");
         list.add("5555");
        //遍历的三种方式
        // 方式1:for+下标

        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i)+ " ");
        }
         System.out.println();
        // 方式2: foreach
        for(String string :list){
            System.out.print(string+ " ");
        }
        System.out.println();

        // 方式3 :利用迭代器遍历
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

}

ArrayList 扩容机制

  1. 检测是否真正需要扩容,如果是,调用grow准备扩容;
  2. 根据需要扩容的大小,一般按照1.5倍大小进行扩容;
    oldCapacity 是存储数据数组的大小;
    int newCapacity = oldCapacity + (oldCapacity >> 1);(库函数中

注意

不能无限制的扩容,导致内存不足;

  1. 使用 copyOf 进行扩容

模拟实现 ArrayList

代码如下

import java.util.Arrays;

//模拟实现ArrayList
public class ArrayList<E> {
    private E[] elementData;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

   // 构造方法
       ArrayList(){
          this ( DEFAULT_CAPACITY);
       }
      ArrayList(int initCapacity){
         if(initCapacity<=0) {
             initCapacity= DEFAULT_CAPACITY;
         }
         elementData=(E[]) new Object[initCapacity];
      }

      public int size(){
           return size;
      }
       public boolean isEmpty(){
           return 0 == size;
       }

      // 尾插
       public boolean add(E e){
           //考虑扩容问题
           //ensureCapacity(size+1);
           elementData[size++] = e;
          return true;
       }

       //在任意 index 位置插入数据
       public void add(int index,E e){
           if(index < 0|| index > size){
               throw new ArrayIndexOutOfBoundsException("index 越界");
           }
           ensureCapacity(size);
           //将index及其往后的元素往后进行搬移,腾出的位置放 e
           for(int i = size-1;i >= index;i--){
               elementData[i+1] = elementData[i];
           }
           elementData[index]=e;
           size++;
       }



       //返回 e 第一次出现的位置
       public int indexOf(E e){
           for (int i = 0; i < size ; i++) {
               if (e.equals(elementData[i])){
                   return i;
               }
           }
           return -1;
       }



       // 删除元素e
       public boolean remove(E e){
        int index=indexOf(e);
        if(-1==index){
            return false ;
        }
        remove(e);
        return true;
       }


       // 删除index位置上元素
       public E remove(int index) {
           if (index < 0 || index > size) {
               throw new ArrayIndexOutOfBoundsException("index 越界");
           }
           E ret=elementData[index];
           for (int i = index + 1; i < size; i++) {
               elementData[i - 1] = elementData[i];
           }
           size--;
           return ret;
       }

      获取index位置上的元素
       public E get(int index){
           if (index < 0 || index > size) {
               throw new ArrayIndexOutOfBoundsException("index 越界");
           }
           return elementData[index];
       }


       //将index位置上的元素设为e
       public E set(int index,E e){
           if (index < 0 || index > size) {
               throw new ArrayIndexOutOfBoundsException("index 越界");
           }
           elementData[index]=e;
           return e;
       }

        清空
       public void clear(){
           size=0;
           for (int i = 0; i < size ; i++) {
               elementData[i]=null;
           }
       }

       // 获取e最后一次出现的位置
       public int lastIndexOf(E e){
           for (int i = size-1; i >= 0 ; i--) {
               if(e.equals(elementData[i])){
                   return i;
               }
           }
           return -1;
       }


       //判断是否包含e
       public boolean contains(E e){

           return -1 !=indexOf(e);
       }

        获取[fromIndex, toIndex)的一个子序列
       ArrayList<E> subList(int from,int to){
           if(from>to){
               throw new IllegalArgumentException();
           }
           int newSize=to-from;
           ArrayList<E> list =new ArrayList<>(newSize);
           while(from < to){
               list.add(elementData[from]);
               from++;
           }
           return list;
       }
      //扩容
       private void ensureCapacity(int size){
           int oldCapacity=elementData.length;
           if(size>oldCapacity){
               int newCapacity=oldCapacity+(oldCapacity>>1);
               elementData= Arrays.copyOf(elementData,newCapacity);
           }
       }

    @Override
    public String toString() {
        String s = "[";
        for (int i = 0; i < size-1; i++) {
            s+=elementData[i];
            s+=",";
        }
        s+=elementData[size-1];
        s+="]";
        return s;
    }
       public static void main(String[] args) {
           //  测试所写的方法
           ArrayList<Integer> al=new ArrayList<>(10);
           al.add(1);
           al.add(2);
           al.add(3);
           al.add(4);
           al.add(5);
           System.out.println(al);   //测试尾插
           al.add(0,0);
           System.out.println(al);   //测试在任意位置插入
           al.remove(1);
           System.out.println(al);   //删除
          al.remove(5);
           System.out.println(al);  //删除
           System.out.println(al.get(1));  //获取1号位置的元素
           al.set(3,7); //将3号位置的元素设置为7
           System.out.println(al);
           System.out.println(al.contains(3)); //包含返回true
           System.out.println(al.contains(5));  //不包含,返回false
           System.out.println(al.subList(0,2)); //截取[0,2)
           al.add(1,0);
           al.add(3,0);
           System.out.println(al);
           System.out.println(al.indexOf(0));   //返回 0第一次出现的位置
           System.out.println(al.lastIndexOf(0)); // 获取0最后一次出现的位置
            al.clear();
           System.out.println(al.size);
       }
}

欢迎大佬指正~~!!!在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值