《資料結構與演算法: C#語言描述》第1章讀書筆記

來源:互聯網
上載者:User

在這本書第一章的1.2.1節中結構的範例程式碼(請參見網址:http://book.51cto.com/art/200905/123578.htm)可能需要修改,因為奇怪的是:屬性寫了卻沒用到。將其中的ToString()重寫方法和Initials()方法改為:

public override string ToString(){    return (String.Format("{0} {1} {2}", firstName, middleName, lastName));}public string Initials(){    return (String.Format("{0} {1} {2}", firstName.Substring(0, 1), middleName.Substring(0, 1), lastName.Substring(0, 1)));}

在上面的範例程式碼片斷中,fname改為firstName,mname改為middleName,lname改為lastName。這樣的程式修改後實現了直接在該結構內調用它的屬性,通過後面的new 結構的建構函式賦屬性值。

接下來,在1.3.3節中程式的Count方法應由方法修改為屬性,而不應使用方法。

public int Count{    get    {        return InnerList.Count;    }}

Count部分的範例程式碼片斷

Console.WriteLine("Number of names: " + names.Count);names.Remove("David");Console.WriteLine("Number of names: " + names.Count);names.Clear();Console.WriteLine("Number of names: " + names.Count);

Main()方法部分的範例程式碼片斷

Count的輸出結果為:4,3,0。這樣的程式修改後才是真正的實現Collection類。

在1.7節練習 第2題:請為Collection類添加Insert方法、Contains方法、IndexOf方法、RemoveAt方法。

public void Insert(int index, object item){    InnerList.Insert(index, item);}public bool Contains(object item){    return InnerList.Contains(item);}public int IndexOf(object item){    return InnerList.IndexOf(item);}public int IndexOf(object item, int startIndex){    return InnerList.IndexOf(item, startIndex);}public int IndexOf(object item, int startIndex, int count){    return InnerList.IndexOf(item, startIndex, count);}public void RemoveAt(int index){    InnerList.RemoveAt(index);}

練習第3題:請使用Timing類來比較向Collection類和ArrayList類分別添加了1 000 000個整數時的效能。

using System;class TestDemo{    static void BuildArray(Collection arr)    {        for (int i = 0; i <= 1000000; i++)        {            arr.Add(i);        }    }    static void DisplayNums(Collection arr)    {        foreach(int i in arr)        {            Console.Write(i + " ");        }    }    static void Main(string[] args)    {        Collection nums = new Collection();        BuildArray(nums);        Timing obj = new Timing();        obj.startTime();        DisplayNums(nums);        obj.stopTime();        Console.WriteLine("Time: " + obj.Result.TotalSeconds);    }}

上面的程式運行結果為:

這是 Collection 類的程式實現。ArrayList類的程式實現與之類同,本貼文略過不寫了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.