黑马程序员---集合类数据结构

来源:互联网 发布:英国情报机构 大数据 编辑:程序博客网 时间:2024/06/07 00:10

集合类:ArrayList与HashTable

arraylist集合类可看做是长度可变的数组,存的是object 对象。增删插数据时会自动变换长度,使用更方便。

常用方法与属性:

count  总数

Add(object)  添加一个对象元素

AddRange(Icollection) 添加一个实现Icollection接口的对象元素,将其成员遍历后依次添加。

Insert(index,item) 将item元素插入到index位置

Remove(object) 找到object元素并将其移除

RemoveAt(index) 将位置为index的元素移除

Clear() 将集合中的元素清空 

Sort() Reverse() 将 集合中的元素排序

Contains(item) 判断是否存在item元素

indexOf(item) LastindexOf(item)查找元素的位置


自己定义所需的集合类型,添加索引器(本质是属性),将自定义集合类当做数组使用。

class persons

{

    ArrayList al;

pubic persons()

{

al=new ArrayList();

}

public person this[int  index]

{

get{ return (person) al[index];  }

set{ al[index]=value;}


}

public int Add(person p)

{

al.Add(p);

}

}


 HashTable集合类,存储键值对形式的数据,以键为索引而不是以 数字为索引,从而更方便的查询数据,

HashTable ht=new HashTable();

ht.Add(key,value);


集合类的遍历

arraylist: for(int i =0;i<al.counts;i++)

             {   }

hashtable :  foreach ( var/DictionaryEntry temp in ht)

     {  }

泛型:集合类arraylist和hashtable中存储的都是object类型,使用时要来回转换,故我们可定义存储数据类型,直接使用,不需转换

List<类型名> LInt=new List<类型名> ();

Dictionary<key类型名,value类型名>   dir =new  Dictionary<key类型名,value类型名> ();









0 0