集合类Array List HashTable实例操作练习

2019-05-20 12:52:04于海丽

}
}
}
class Program {
static void Main( string[] args) {
Student xyy = new Student( "小月月" , 14);
Student fj = new Student( "凤姐" , 18);
Student fr = new Student( "芙蓉姐姐" , 19);
Student xl = new Student( "犀利哥" , 20);
ArrayList student = new ArrayList();
student.Add(xyy); //添加 也可以使用AddRange
student.Add(fj);
student.Add(fr);
student.Add(xl);
//移除
//student.Remove(fj);//这里移除的就是对象 而不是值
//student.RemoveAt(1);//索引移除
//移除不掉fj 因为Remove后是object 按索引移除
//Student stu = new Student("凤姐", 18);
//student.Remove(stu);
//Console.WriteLine(student.Contains(stu));//false 通过索引检索 因为stu与fj地址是不一样的
//遍历
for (int i = 0; i < student.Count; i++) {
Student s = student[i] as Student; //因为添加前发生装箱操作 所以 现在需要拆箱 student[i]是不能点出name的
Console .WriteLine(s.Name);
}
ArrayList ary = new ArrayList();
ary.Add( "凤姐" );
ary.Add( "小月月" );
//string类同样是引用类型 但是这里有些特别
string name = "凤姐" ;
Console .WriteLine(ary.Contains(name));//string比较的是内容 所以返回true
//根据学生姓名 获取学生对象 虽然ArrayList可以实现 但是相当的复杂 而且效率低下 所以接下来学习HashTable
Console .Read();
}
}
}

c、HashTable

using System;
using System.Collections;
namespace _10_HashTable {
class Student {
public Student(string name, int age) {
this .name = name;
this .age = age;
}
private string name;
public string Name {
get {
return name;
}
set {
name = value ;
}
}
private int age;
public int Age {
get {
return age;
}
set {
age = value ;
}
}
}
class Program {
static void Main( string[] args) {
//仍然使用Student的类来实现
//Hashtable键值对形式 key value 相当于字典 能根据学生的姓名快速的找到对象
Student xyy = new Student( "小月月" , 14);
Student fj = new Student( "凤姐" , 18);
Student fr = new Student( "芙蓉姐姐" , 19);
Student xl = new Student( "犀利哥" , 20);
Hashtable student = new Hashtable();
student.Add( "小月月" , xyy);
student.Add( "凤姐" , fj);
student.Add( "芙蓉姐姐" , fr);
student.Add( "犀利哥" , xl);
//student.Add("犀利哥",xl);//错误 字典中的关键字key 不允许重复 所以不能再添加犀利哥
//移除 因为没有索引 所以没有RemoveAt()
student.Remove( "小月月" );//根据key来移除
student.Clear();
student.ContainsKey( "凤姐" );//判断是不是含有这个键
//遍历 因为字典没有索引 所以不能使用for来遍历 只能使用foreach
//按key遍历 经常用
foreach (object key in student.Keys) {
Student stu = student[key] as Student;
Console .WriteLine(key);