C 泛型集合

2021-09-28 10:32:07 字數 2357 閱讀 8989

陣列的侷限性:

***陣列元素個數是固定的,陣列一但定義,就無法改變元素總數,如果需求變化,就要修改原始碼。

***如果初始化元素總數非常大,則會造成空間浪費。

集合的特點:

***根據需求動態增加元素個數,沒有限制。

list泛型集合的特點:元素可以擺放無序

***表示泛型,t是type的縮寫,表示當前不確定具體型別。

***可以根據使用者的實際需要,確立當前集合需要存放的資料型別,一但確定不可改變。

list泛型集合的儲存結構:

泛型集合要求:

***使用泛型集合只能新增一種型別的資料,資料取出後無需強制轉換。

list使用前的準備工作:

***引入命名空間using system.collections.generic;

***確定儲存型別:liststudent = new list();

常用方法:

***新增元素:add();

***刪除元素:removeat(索引)

常用屬性:

***元素個數:count

遍歷集合:

foreach(student stu in students)

例子:

class program

);//初始化器

//集合初始化器

listnamelist = new list();

//建立集合物件

liststulist = new list();

stulist.add(objstudent1);//乙個乙個往集合中新增元素

stulist.add(objstudent2);

stulist.add(objstudent3);

stulist.add(objstudent4);

//以陣列的形式往集合中新增元素,不用乙個乙個新增

//獲取元素的個數

console.writeline("元素總數:",stulist.count);

//刪除元素

stulist.remove(objstudent2);//按元素刪除

stulist.removeat(0);//按元素的索引刪除

//插入乙個物件

stulist.insert(0,new student(1006,"but"));//在所引處新增乙個元素

console.writeline(objstudent1.studentname);//get設定

//遍歷

foreach(student i in stulist)

console.readline();

}

泛型集合dictionary:(儲存基於雜湊表)元素擺放有序,通過序號k找到物件v***dictionary通常稱為字典,約束集合中元素的型別。

***編譯時檢查型別約束,無需裝箱拆箱操作,與雜湊表操作類似

dictionary的儲存結構:

例子:

dictionarystus = new dictionary();

stus.add("joday", objstudent1);

stus.add("lucy", objstudent2);

//取出元素

console.writeline(stus["joday"].studentid);

foreach (student value in stus.values) //對值遍歷,鍵、值一次遍歷只能遍歷乙個

foreach(string key in stus.keys)//對鍵進行遍歷

C 集合 泛型集合

非泛型集合的類和介面位於system.collections命名空間。泛型集合的類和介面位於system.collections.generic命名空間。普通集合 arraylist 值 有序不唯一 hashtable key 必須唯一 可為空 不能為null value 可重複 能為空和null ...

C 泛型 泛型集合Dictionary

在system.collections.generic命名空間中,與arraylist相對應的泛型集合是list,與hashtable相對應的泛型集合是dictionary,其儲存資料的方式與雜湊表相似,通過鍵 值來儲存元素,並具有泛型的全部特徵,編譯時檢查型別約束,讀取時無須型別轉換。本儲存的例子...

C 泛型集合

集合是oop中的乙個重要概念,c 中對集合的全面支援更是該語言的精華之一。為什麼要用泛型集合?在c 2.0之前,主要可以通過兩種方式實現集合 a.使用arraylist 直接將物件放入arraylist,操作直觀,但由於集合中的項是object型別,因此每次使用都必須進行繁瑣的型別轉換。b.使用自定...