ArrayList动态增加原理

gaojingbinboss 2011-03-01 12:05:26
ArrayList容量动态增加是什么原理
...全文
130 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
看看 ArrayList 的源代码:
public virtual int Add(object value)
{
if (this._size == this._items.Length)
{
this.EnsureCapacity(this._size + 1);
}
this._items[this._size] = value;
this._version++;
return this._size++;
}


private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}


public virtual int Capacity
{
get
{
return this._items.Length;
}
set
{
if (value < this._size)
{
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
if (value != this._items.Length)
{
if (value > 0)
{
object[] destinationArray = new object[value];
if (this._size > 0)
{
Array.Copy(this._items, 0, destinationArray, 0, this._size);
}
this._items = destinationArray;
}
else
{
this._items = new object[4];
}
}
}
}


[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public virtual void Remove(object obj)
{
int index = this.IndexOf(obj);
if (index >= 0)
{
this.RemoveAt(index);
}
}


public virtual void RemoveAt(int index)
{
if ((index < 0) || (index >= this._size))
{
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
this._size--;
if (index < this._size)
{
Array.Copy(this._items, index + 1, this._items, index, this._size - index);
}
this._items[this._size] = null;
this._version++;
}


每当Add的时候,如果预留的空间满了,就会申请多一倍的空间。而申请更多空间时会拷贝对象引用数组。

而当你删除一个对象,它不但要在数组上找到并删除这个对象的引用,而且要将随后的所有对象引用全都拷贝一次。
threenewbee 2011-03-02
  • 打赏
  • 举报
回复
无非是两种算法:

固定式:申请一块存储器。连续存储元素,如果满了,就重新申请一块更大的空间,再拷贝进去。这种数据结构的读性能很高,写性能受影响。

链表式:用链表来存储元素。当需要增加一个元素的时候,就为新元素申请空间,并且将新元素链接到链表里面。这种数据结构容易修改、删除、添加元素。但是随机访问性能差。

ArrayList 使用的是前面的算法。
  • 打赏
  • 举报
回复
直接msdn
机器人 2011-03-01
  • 打赏
  • 举报
回复
根据capacity定义,不够的时候调整容量。

http://msdn.microsoft.com/zh-cn/library/y52x03h2(v=vs.80).aspx
lizhibin11 2011-03-01
  • 打赏
  • 举报
回复
不停的拷贝

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧