动态数组

Sujie2541 2010-03-25 09:26:58
ArrayList咋样用?
...全文
97 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
winnerfat 2010-03-25
  • 打赏
  • 举报
回复
参看MSDN
futureisgood 2010-03-25
  • 打赏
  • 举报
回复
参看MSDN
zyjj521 2010-03-25
  • 打赏
  • 举报
回复
用泛型吧
huan_jin 2010-03-25
  • 打赏
  • 举报
回复
List范型,感觉更好一些吧
Snowdust 2010-03-25
  • 打赏
  • 举报
回复
建议使用List范型,不用装箱和拆箱:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);

int a = list[3]; //a的值为2;
Peter200694013 2010-03-25
  • 打赏
  • 举报
回复
给个例子:

默认Capacity是16,使用TrimToSizie()可以使Count和Capacity相等。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
al.Add(100);//单个添加
foreach (int number in new int[6] { 9, 3, 7, 2, 4, 8 })
{
al.Add(number);//集体添加方法一
}
int[] number2 = new int[2] { 11, 12 };
al.AddRange(number2);//集体添加方法二
al.Remove(3);//移除值为3的
al.RemoveAt(3);//移除第3个
ArrayList al2 = new ArrayList(al.GetRange(1, 3));

//新ArrayList只取旧ArrayList一部份

Console.WriteLine("遍历方法一:");
foreach (int i in al)//不要强制转换
{
Console.WriteLine(i);//遍历方法一
}

Console.WriteLine("遍历方法二:");
for (int i = 0; i < al2.Count; i++)//数组是length
{
int number = (int)al2[i];//一定要强制转换
Console.WriteLine(number);//遍历方法二

}
}
}
}

shixiujin 2010-03-25
  • 打赏
  • 举报
回复
@lz:
可以将ArrayList类型看作为一个动态的数组,并且其元素类型为object。(所谓动态数组,即随着元素的增加其对象的大小也随之增加)

首先引用相关的命名空间:
using System.Collections;
static void Main()
{
ArrayList list = new ArrayList();
for(int item = 0; item < 10; item++)
list.Add(item);

Console.WriteLine("显示其中的数据:");
foreach(int i in list)
Console.Write(i.ToString() + " , ");

Console.WriteLine();
}

希望对您有所帮助!
wzp144650 2010-03-25
  • 打赏
  • 举报
回复
MSDN看呀
yingzhilian2008 2010-03-25
  • 打赏
  • 举报
回复
支持用泛型

110,534

社区成员

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

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

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