ArrayList用法实例

采摘处:http://hi.baidu.com/wlw7758/blog/item/9e51bb7e73cac53b0cd7daf4.html




System.Collections.ArrayList类是一个特殊的数组。通过添加和删除元素,就可以动态改变数组的长度。

一.优点

1。支持自动改变大小的功能
2。可以灵活的插入元素
3。可以灵活的删除元素

二.局限性

跟一般的数组比起来,速度上差些

三.添加元素

1.public virtual int Add(object     value);

将对象添加到ArrayList的结尾处

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
内容为abcde

2.public virtual void Insert(intindex,object value);

将元素插入ArrayList的指定索引处

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Insert(0,"aa");

结果为aaabcde

3.public virtual void InsertRange(int index,ICollectionc);

将集合中的某个元素插入ArrayList的指定索引处

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
ArrayList list2=new ArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2,list2);

结果为abtttttcde

四.删除

a)public virtual void Remove(object obj);

从ArrayList中移除特定对象的第一个匹配项,注意是第一个

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Remove("a");

结果为bcde

2.public virtual void RemoveAt(int index);

移除ArrayList的指定索引处的元素

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveAt(0);

结果为bcde

3.public virtual void RemoveRange(int index,int count);

从ArrayList中移除一定范围的元素。Index表示索引,count表示从索引处开始的数目

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveRange(1,3);

结果为ae

4.public virtual void Clear();

从ArrayList中移除所有元素。

五.排序

a)public virtual void Sort();

对ArrayList或它的一部分中的元素进行排序。

ArrayLista List=new ArrayList();
aList.Add("e");
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
DropDownList1.DataSource=aList;

//DropDownList DropDownList1;
DropDownList1.DataBind();

结果为eabcd

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Sort();//排序
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();

结果为abcde

b)public virtual void Reverse();

将ArrayList或它的一部分中元素的顺序反转。

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Reverse();//反转
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
结果为edcba

六.查找

a)public virtual int IndexOf(object);
b)public virtual int IndexOf(object,int);
c)public virtual int IndexOf(object,int,int);

返回ArrayList或它的一部分中某个值的第一个匹配项的从零开始的索引。没找到返回-1。

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
int nIndex=aList.IndexOf(“a”);//1
nIndex=aList.IndexOf(“p”);//没找到,-1
d)public virtual int LastIndexOf(object);
e)public virtual int LastIndexOf(object,int);
f)public virtual int LastIndexOf(object,int,int);

返回ArrayList或它的一部分中某个值的最后一个匹配项的从零开始的索引。

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("a");//同0
aList.Add("d");
aList.Add("e");
int nIndex=aList.LastIndexOf("a");//值为2而不是0

g)public virtual bool Contains(objectitem);

确定某个元素是否在ArrayList中。包含返回true,否则返回false

七.其他

1.public virtual int Capacity{get;set;}

获取或设置ArrayList可包含的元素数。

2.public virtual int Count{get;}

获取ArrayList中实际包含的元素数。
Capacity是ArrayList可以存储的元素数。Count是ArrayList中实际包含的元素数。Capacity总是大于或等于Count。如果在添加元素时,Count超过Capacity,则该列表的容量会通过自动重新分配内部数组加倍。
如果Capacity的值显式设置,则内部数组也需要重新分配以容纳指定的容量。如果Capacity被显式设置为0,则公共语言运行库将其设置为默认容量。默认容量为16。
在调用Clear后,Count为0,而此时Capacity切是默认容量16,而不是0

3.public virtual void TrimToSize();

将容量设置为ArrayList中元素的实际数量。
如果不向列表中添加新元素,则此方法可用于最小化列表的内存系统开销。
若要完全清除列表中的所有元素,请在调用TrimToSize之前调用Clear方法。截去空ArrayList会将ArrayList的容量设置为默认容量,而不是零。

ArrayLista List=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");//Count=5,Capacity=16,
aList.TrimToSize();//Count=Capacity=5;

ArrayList

原文出处:

http://blog.java-cn.com/more.asp?name=luolei&id=415

ArrayList是List接口的一个可变长数组实现。实现了所有List接口的操作,并允许存储null值。除了没有进行同步, ArrayList基本等同于Vector。在Vector中几乎对所有的方法都进行了同步,但ArrayList仅对writeObject和 readObject进行了同步,其它比如add(Object)、remove(int)等都没有同步。

ArrayList是List接口的一个可变长数组实现。实现了所有List接口的操作,并允许存储null值。除了没有进行同步, ArrayList基本等同于Vector。在Vector中几乎对所有的方法都进行了同步,但ArrayList仅对writeObject和 readObject进行了同步,其它比如add(Object)、remove(int)等都没有同步。

1.存储

ArrayList使用一个Object的数组存储元素。
private transient Object elementData[];
ArrayList实现了java.io.Serializable接口,这儿的transient标示这个属性不需要自动序列化。下面会在writeObject()方法中详细讲解为什么要这样作。

2.add和remove


    public boolean add(Object o) {
      ensureCapacity(size + 1);  // Increments modCount!!
      elementData[size++] = o;
    return true;
      }

注意这儿的ensureCapacity()方法,它的作用是保证elementData数组的长度可以容纳一个新元素。在“自动变长机制”中将详细讲解。
    public Object remove(int index) {
      RangeCheck(index);
      modCount++;
      Object oldValue = elementData[index];
    int numMoved = size - index - 1;
    if (numMoved > 0)
          System.arraycopy(elementData, index+1, elementData, index,
                   numMoved);
      elementData[--size] = null; // Let gc do its work
    return oldValue;
      }

RangeCheck()的作用是进行边界检查。由于ArrayList采用一个对象数组存储元素,所以在删除一个元素时需要把后面的元素前移。删除一个元素时只是把该元素在elementData数组中的引用置为null,具体的对象的销毁由垃圾收集器负责。
modCount的作用将在下面的“iterator()中的同步”中说明。
注:在前移时使用了System提供的一个实用方法:arraycopy(),在本例中可以看出System.arraycopy()方法可以对同一个数 组进行操作,这个方法是一个native方法,如果对同一个数组进行操作时,会首先把从源部分拷贝到一个临时数组,在把临时数组的元素拷贝到目标位置。

3.自动变长机制

在实例化一个ArrayList时,你可以指定一个初始容量。这个容量就是elementData数组的初始长度。如果你使用:
      ArrayList list = new ArrayList();

则使用缺省的容量:10。
    public ArrayList() {
    this(10);
      }

ArrayList提供了四种add()方法,

  • public boolean add(Object o)
  • public void add(int index, Object element)
  • public boolean addAll(Collection c)
  • public boolean addAll(int index, Collection c)


在每一种add()方法中,都首先调用了一个ensureCapacity(int miniCapacity)方法,这个方法保证elementData数组的长度不小于miniCapacity。ArrayList的自动变长机制就是在这个方法中实现的。
    public void ensureCapacity(int minCapacity) {
      modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {
          Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
          newCapacity = minCapacity;
          elementData = new Object[newCapacity];
          System.arraycopy(oldData, 0, elementData, 0, size);
      }
      }

从这个方法实现中可以看出ArrayList每次扩容,都扩大到原来大小的1.5倍。
每种add()方法的实现都大同小异,下面给出add(Object)方法的实现:
    public boolean add(Object o) {
      ensureCapacity(size + 1);  // Increments modCount!!
      elementData[size++] = o;
    return true;
      }

4.iterator()中的同步

在父类AbstractList中定义了一个int型的属性:modCount,记录了ArrayList结构性变化的次数。
    protected transient int modCount = 0;

在ArrayList的所有涉及结构变化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。这些方法每调用一次,modCount的值就加1。
注:add()及addAll()方法的modCount的值是在其中调用的ensureCapacity()方法中增加的。

AbstractList中的iterator()方法(ArrayList直接继承了这个方法)使用了一个私有内部成员类Itr,生成一个Itr对象(Iterator接口)返回:
    public Iterator iterator() {
    return new Itr();
      }

Itr实现了Iterator()接口,其中也定义了一个int型的属性:expectedModCount,这个属性在Itr类初始化时被赋予ArrayList对象的modCount属性的值。
    int expectedModCount = modCount;

注:内部成员类Itr也是ArrayList类的一个成员,它可以访问所有的AbstractList的属性和方法。理解了这一点,Itr类的实现就容易理解了。

在Itr.hasNext()方法中:
    public boolean hasNext() {
        return cursor != size();
      }

调用了AbstractList的size()方法,比较当前光标位置是否越界。

在Itr.next()方法中,Itr也调用了定义在AbstractList中的get(int)方法,返回当前光标处的元素:
    public Object next() {
        try {
          Object next = get(cursor);
          checkForComodification();
          lastRet = cursor++;
        return next;
          } catch(IndexOutOfBoundsException e) {
          checkForComodification();
        throw new NoSuchElementException();
          }
      }

注意,在next()方法中调用了checkForComodification()方法,进行对修改的同步检查:
    final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      }

现在对modCount和expectedModCount的作用应该非常清楚了。在对一个集合对象进行跌代操作的同时,并不限制对集合对象的元素进行操 作,这些操作包括一些可能引起跌代错误的add()或remove()等危险操作。在AbstractList中,使用了一个简单的机制来规避这些风险。 这就是modCount和expectedModCount的作用所在。

5.序列化支持

ArrayList实现了java.io.Serializable接口,所以ArrayList对象可以序列化到持久存储介质中。ArrayList的主要属性定义如下:

  • private static final long serialVersionUID = 8683452581122892189L;
  • private transient Object elementData[];
  • private int size;


可以看出serialVersionUID和size都将自动序列化到介质中,但elementData数组对象却定义为transient了。也就是说 ArrayList中的所有这些元素都不会自动系列化到介质中。为什么要这样实现?因为elementData数组中存储的“元素”其实仅是对这些元素的 一个引用,并不是真正的对象,序列化一个对象的引用是毫无意义的,因为序列化是为了反序列化,当你反序列化时,这些对象的引用已经不可能指向原来的对象 了。所以在这儿需要手工的对ArrayList的元素进行序列化操作。这就是writeObject()的作用。
    private synchronized void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
    // Write out element count, and any hidden stuff
      s.defaultWriteObject();
   // Read in all elements in the proper order.
    for (int i=0; i<size; i++)
              elementData[i] = s.readObject();
      }




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值