ArrayList

  
	private static final long serialVersionUID = 8683452581122892189L;
	//不支持序列化
    private transient E[] elementData;
    private int size;
   
	//指定初始容量initialCapacity
    public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = (E[])new Object[initialCapacity];
    }

    public ArrayList() {
    //初始容量10
	this(10);
    }

    public ArrayList(Collection<? extends E> c) {
        size = c.size();
        // 设置容量1.1倍最大为最大整数
        int capacity = (int) Math.min((size*110L)/100, Integer.MAX_VALUE);
		//复制数组,影响性能
        elementData = (E[]) c.toArray(new Object[capacity]);
    }

    /**
     * 
     */
    public void trimToSize() {
	modCount++;
	//数组长度
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
	    Object oldData[] = elementData;
		//重设长度为size
	    elementData = (E[])new Object[size];
		//复制数组,对性能有影响
	    System.arraycopy(oldData, 0, elementData, 0, size);
	}
    }

    public void ensureCapacity(int minCapacity) {
    //modCount记录了ArrayList结构性变化的次数
	modCount++;
	//数组现有容量
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
		//增长策略1.5+1,如果还小则长度为新长度
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
	    //创建新数组
	    elementData = (E[])new Object[newCapacity];
		//数组复制
	    System.arraycopy(oldData, 0, elementData, 0, size);
	}
    }

    public int size() {
	//数组元素数量
	return size;
    }

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

    public boolean contains(Object elem) {
	//是否能索引到
	return indexOf(elem) >= 0;
    }

    public int indexOf(Object elem) {
	//检索null对象
	if (elem == null) {
	    for (int i = 0; i < size; i++)
		if (elementData[i]==null)
		    return i;
	} else {
		//顺序检索
	    for (int i = 0; i < size; i++)
		if (elem.equals(elementData[i]))
		    return i;
	}
	return -1;
    }
    //倒序索引
    public int lastIndexOf(Object elem) {
	if (elem == null) {
	    for (int i = size-1; i >= 0; i--)
		if (elementData[i]==null)
		    return i;
	} else {
	    for (int i = size-1; i >= 0; i--)
		if (elem.equals(elementData[i]))
		    return i;
	}
	return -1;
    }
    //数组复制
    public Object clone() {
	try { 
	    ArrayList<E> v = (ArrayList<E>) super.clone();
	    v.elementData = (E[])new Object[size];
	    System.arraycopy(elementData, 0, v.elementData, 0, size);
	    v.modCount = 0;
	    return v;
	} catch (CloneNotSupportedException e) { 
	    // this shouldn't happen, since we are Cloneable
	    throw new InternalError();
	}
    }
    //返回包含此列表中所有元素的数组
    public Object[] toArray() {
	Object[] result = new Object[size];
	System.arraycopy(elementData, 0, result, 0, size);
	return result;
    }

    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.
		newInstance(a.getClass().getComponentType(), size);
	System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    
    public E get(int index) {
	//检查范围
	RangeCheck(index);

	return elementData[index];
    }

    public E set(int index, E element) {
	//检查范围
	RangeCheck(index);

	E oldValue = elementData[index];
	elementData[index] = element;
	return oldValue;
    }

    /**
     * 新增
     */
    public boolean add(E o) {
    //数组扩容
	ensureCapacity(size + 1);  // Increments modCount!!
	//赋值
	elementData[size++] = o;
	return true;
    }

    public void add(int index, E element) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);
    //扩容
	ensureCapacity(size+1);  // Increments modCount!!
	//index之后元素后移一位,size增1
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++;
    }


    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);
		//size元素设为null,size-1
	elementData[--size] = null; // Let gc do its work

	return oldValue;
    }

    public boolean remove(Object o) {
	if (o == 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; // Let gc do its work
    }

    public void clear() {
	modCount++;

	// Let gc do its work
	for (int i = 0; i < size; i++)
	    elementData[i] = null;

	size = 0;
    }

    public boolean addAll(Collection<? extends E> c) {
	Object[] a = c.toArray();
        int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
	return numNew != 0;
    }

    public boolean addAll(int index, Collection<? extends E> c) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: " + index + ", Size: " + size);

	Object[] a = c.toArray();
	int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount

	int numMoved = size - index;
	if (numMoved > 0)
	    System.arraycopy(elementData, index, elementData, index + numNew,
			     numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
	size += numNew;
	return numNew != 0;
    }

    protected void removeRange(int fromIndex, int toIndex) {
	modCount++;
	int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

	// Let gc do its work
	int newSize = size - (toIndex-fromIndex);
	while (size != newSize)
	    elementData[--size] = null;
    }

    private void RangeCheck(int index) {
	if (index >= size)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);
    }
    //重载下面方法,只序列化了数组中有意义的对象,而pos>size的对象无须序列化和反序列化
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
	int expectedModCount = modCount;
	// Write out element count, and any hidden stuff
	s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

	// Write out all elements in the proper order.
	for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

 	if (modCount != expectedModCount) {
	    throw new ConcurrentModificationException();
	}
    }


    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
	// Read in size, and any hidden stuff
	s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = (E[])new Object[arrayLength];

	// Read in all elements in the proper order.
	for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}
### 在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、付费专栏及课程。

余额充值