码迷,mamicode.com
首页 > Windows程序 > 详细

C#中 ArrayList 的使用

时间:2017-11-17 16:16:05      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:city   trim   com   方法   清空   循环   test   comm   void   

using System.Collections;
public class TestStudent
{
   public static void main(String args [])
   {
   //建立ArrayList对象
   ArrayList students = new ArrayList();
   //实例化几个Student类对象
   Student rose = new Student("rose",25,"reading");
   Student jack = new Student("jack",28,"singing");
   Student mimi = new Student("mimi",26,"dancing");
   //利用ArrayList类的add()方法添加元素
   students.add(rose);
   students.add(jack);
   students.add(mimi);
   //利用ArrayList的Count属性查看该集合中的元素数量
   int number = students.Count;
    Console.WriteLine("共有元素" + number + "个");
   //读取单个元素,因为存入ArrayList中的元素会变为Object类型,
   //所以,在读取时间,
   Student stu = students[0] as Student;
   stu.say();
   //遍历元素 -- 通过索引
   for(int i = 0;i < students.Count;i ++)
   {
    Student a = students[i] as Student;
    a.say();
   }
   //利用foreach循环
   foreach(Object o in students)
   {
     Student b = o as Student;
     b.say();
   }
   //删除元素 通过索引删除
   students.removeAt(0);
   //删除元素,  通过对象名
   students.remove(jack);
   //清空元素
   students.Clear();
   //我们知道,ArrayList的容量会随着我们的需要自动按照一定规律
   //进行填充,当我们确定不再添加元素时,我们要释放多余的空间
   //这就用到了Capacity属性和TrimtoSize()方法
   //利用Capacity属性可以查看当前集合的容量  
   //利用TrimtoSize()方法可以释放多余的空间
 
   //查看当前容量
   int number = students.Capacity;
   //去除多余的容量
   students.TrimtoSize();
   }
}

C#中 ArrayList 的使用

标签:city   trim   com   方法   清空   循环   test   comm   void   

原文地址:http://www.cnblogs.com/Kirsi/p/7851800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!