ArrayList

本文深入探讨了ArrayList的工作原理,包括其构造函数、扩容机制、增删操作等关键环节,并对比了与LinkedList的性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ArrayList作为一个新手最常用的集合,一直都没有研究他内部的实现,既然下定决心要写博客,就不管什么大小事都记录一下吧,或许真的有用呢?
首先ArrayList有三个构造函数(jdk8)
 1. new ArrayList();  //初始化一个空数组

 2. new ArrayList(int initialCapacity); //创建指定大小的数组

 3. new ArrayList(Collection<? extends E> c);//集合转换或复制。如LinkedList-->ArrayList

由于ArrayList的内部就是一个数组,所以它的构造函数都是对Object[] elementData进行初始化
下面看看ArrayList是如何实现增删的
 //增加一个元素
 public boolean add(E e) {
        ensureCapacityInternal(size + 1);  
        elementData[size++] = e;
        return true;
 }

 //在指定位置增加一个元素
 public void add(int index, E element) {
        rangeCheckForAdd(index);//判断角标是否越界
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
  }
 //确认数组是否为空,并且指定初次初始化大小
 private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//DEFAULT_CAPACITY=10
        }
        ensureExplicitCapacity(minCapacity);
 }
 //确认数组是否需要扩容,并调用扩容方法grow
 private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
 }
 //将原来的数组扩大1.5倍
 private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);//数组容量最大是2147483647-8
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
 }

//根据角标删除一元素
public E remove(int index) {
        rangeCheck(index);//检查是否越界

        modCount++;
        E oldValue = elementData(index);//获取要删除的对象并返回

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

 //根据对象删除
 public boolean remove(Object o) {
       //在数组找要删除的元素角标,并用fastRemove删除
        if (o == null) {
        //可以插入null,同时也能删除
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {

           for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
 }

 //删除元素  
 private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
 }



 1. 总体来说add方法都是先检查数组大小是否需要扩容,再赋值。由于ArrayList是非线程安全,在多线线程的情况下,请勿使用,例如2个线程同时对一个数组插入数据,当size==9时,2个线程同时通过了ensureCapacityInternal检查的情况下,就会出现java.lang.ArrayIndexOutOfBoundsException

 2. 每次删除都需要用System.arraycopy对数组进行复制,例如arr[1,2,3,4],若把arr[1]删除,就要把arr[2]后面的内容,复制到原来的位置上,由于不是java的方法不能进入内部查看。

 3. 这样就清楚ArrayList增删没有LinkedList快的原因了。



### 在Unity中使用ArrayList或解决ArrayList相关问题 在Unity开发中,`ArrayList`是非泛型集合类的一部分,允许存储任意类型的元素。尽管C#推荐使用泛型集合(如`List<T>`),但在某些特定场景下,`ArrayList`仍然有其适用性[^4]。 #### 1. 创建和初始化ArrayList 创建一个`ArrayList`对象需要引入`System.Collections`命名空间。以下是一个简单的示例: ```csharp using System.Collections; public class ArrayListExample : MonoBehaviour { void Start() { // 创建一个新的ArrayList实例 ArrayList arrayList = new ArrayList(); // 添加不同类型的元素到ArrayList arrayList.Add("字符串"); arrayList.Add(123); arrayList.Add(45.67f); // 遍历并打印ArrayList中的所有元素 foreach (var item in arrayList) { Debug.Log(item); } } } ``` #### 2. 常见操作:添加、删除和访问元素 `ArrayList`提供了多种方法来操作其中的元素,包括但不限于`Add`、`Remove`、`Insert`和`Contains`等[^4]。 - **添加元素**:使用`Add`方法将新元素追加到集合末尾。 - **插入元素**:使用`Insert`方法在指定索引位置插入新元素。 - **删除元素**:使用`Remove`方法按值删除元素,或使用`RemoveAt`方法按索引删除。 - **查找元素**:使用`Contains`方法检查某个值是否存在于集合中。 以下代码展示了这些操作的具体用法: ```csharp void ExampleOperations() { ArrayList arrayList = new ArrayList { "A", "B", "C" }; // 插入元素 arrayList.Insert(1, "X"); // 删除元素 arrayList.Remove("B"); // 检查元素是否存在 if (arrayList.Contains("X")) { Debug.Log("元素X存在!"); } // 清空整个ArrayList arrayList.Clear(); } ``` #### 3. 解决常见问题 ##### (1) 类型安全问题 由于`ArrayList`是非泛型集合,它会将所有类型视为`Object`处理,这可能导致运行时类型不匹配的问题[^3]。为避免此类问题,建议在访问元素时显式转换类型: ```csharp object element = arrayList[0]; if (element is string str) { Debug.Log(str); } else { Debug.LogError("类型不匹配!"); } ``` ##### (2) 性能问题 当`ArrayList`存储值类型(如`int`或`float`)时,每次添加都会发生装箱操作,而每次访问都会发生拆箱操作,这会导致性能开销[^3]。如果性能是关键因素,推荐使用泛型集合`List<T>`替代`ArrayList`。 #### 4. 替代方案:使用泛型集合`List<T>` 虽然`ArrayList`功能强大,但现代C#开发中更推荐使用泛型集合`List<T>`,因为它提供了更好的类型安全性、更高的性能以及更丰富的API支持[^5]。 以下是一个使用`List<T>`的简单示例: ```csharp using System.Collections.Generic; public class ListExample : MonoBehaviour { void Start() { // 创建一个存储字符串的List List<string> list = new List<string>(); // 添加元素 list.Add("Unity"); list.Add("C#"); // 访问元素 Debug.Log(list[0]); // 遍历列表 foreach (var item in list) { Debug.Log(item); } } } ``` #### 5. 实际应用案例 假设需要动态管理一组游戏对象,可以使用`ArrayList`实现如下功能: ```csharp public class GameObjectManager : MonoBehaviour { private ArrayList gameObjects = new ArrayList(); public void AddGameObject(GameObject obj) { gameObjects.Add(obj); } public void RemoveGameObject(GameObject obj) { gameObjects.Remove(obj); } public void ClearAll() { gameObjects.Clear(); } public void PrintAll() { foreach (var obj in gameObjects) { if (obj is GameObject go) { Debug.Log(go.name); } } } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值