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();
}
}