Interview Abuse Series _ Basic data Structure Chapter _c# set interface _3__ data structures

Source: Internet
Author: User

Question: Please simply say the main collection class in C #, and expound the difference of the principle of realization of several main collection classes.

Thinking:
In any language known as an advanced programming language, the various base collection classes are an essential part. In actual programming, developers are sure to encounter a variety of situations that require large amounts of data to be manipulated, or a large number of objects. In the face of different application scenarios, a variety of different sets of classes here to play their own in the design of the time, the various powerful features. Of course, in C #, there are also a number of powerful collection classes that handle large amounts of data in the application scenario. In the daily practical use, although it is convenient to use, but it is not too much opportunity to go deep into the bottom of the source to understand its specific implementation. Here I would like to take this opportunity to learn more about, but also to learn the promotion of their own an attempt.

The previous article mainly talked about the basic C # several important interface Ilist,list and other direct use in the business of some common structure, and the interface of the generic equivalent interface, and from the source level of a brief comparison of the differences between the various interfaces. This article will continue to talk about some inherited the basic interface of the collection interface and its respective sets of implementation, the same source is a reference. NET4.5 version.

On C # Collection _ Interface Part _idictionary&dictionary

In addition to the list-related interface, C # also has dictionary classes, and dictionaries are used in real-world programming.
//The following section we first look at the IDictionary interface specific content
////The following source code reference. NET Framework 4.5

IDictionary interface and its generic form

==++==////Copyright (c) Microsoft Corporation.
All rights reserved. ==--==/*============================================================ * * * * * * * interface:idictionary * * * * <OWNE R>[...]
</OWNER> * * * * * Purpose:base interface for all dictionaries.
    * * * * * ===========================================================*/namespace System.Collections {using System;

    Using System.Diagnostics.Contracts;
    An IDictionary is a possibly unordered set of key-value pairs.  Keys can be any Non-null object.
    Values can be any object.  
Can look up a value in a IDictionary via the default indexed//property, Items. #if Contracts_full [Contractclass (typeof (Idictionarycontract))] #endif//Contracts_full [System.Runtime.InteropSe Rvices.
        ComVisible (TRUE)] public interface Idictionary:icollection {//interfaces are not serializable The Item property provides methods to read and edit entries//In the Dictionary.
            Object This[object key] {get;
        Set
        }//Returns a collections of the keys in this dictionary.
        ICollection Keys {get;
        }//Returns a collections of the values in this dictionary.
        ICollection Values {get;
        }//Returns Whether this dictionary contains a particular key.

        BOOL Contains (Object key);
        Adds a Key-value pair to the dictionary.

        void Add (Object key, object value);
        Removes all pairs from the dictionary.

        void Clear ();

        BOOL IsReadOnly {get;}

        BOOL Isfixedsize {get;}
        Returns an idictionaryenumerator to this dictionary.

        New IDictionaryEnumerator GetEnumerator ();
        Removes a particular key from the dictionary.
    void Remove (Object key);
/*** above is the behavior defined in the IDictionary interface, and the following is its equivalent generic form ***/
==++==////Copyright (c) Microsoft Corporation.
All rights reserved. ==--==/*============================================================ * * * * * * * interface:idictionary * * * * <OWNE R>[...]
</OWNER> * * * * * Purpose:base interface for all generic dictionaries. * * * * * ===========================================================*/namespace System.Collections.Generic {using Syst
    Em

    Using System.Diagnostics.Contracts;
    An IDictionary is a possibly unordered set of key-value pairs.  Keys can be any Non-null object.
    Values can be any object.  
Can look up a value in a IDictionary via the default indexed//property, Items.  #if Contracts_full [Contractclass (typeof (Idictionarycontract<,>))] #endif//Contracts_full public interface  Idictionary<tkey, tvalue>: Icollection<keyvaluepair<tkey, tvalue>> {//Interfaces are not Serializable//The Item property provides methods toRead and edit entries//in the Dictionary.
            TValue This[tkey key] {get;
        Set
        }//Returns a collections of the keys in this dictionary.
        Icollection<tkey> Keys {get;
        }//Returns a collections of the values in this dictionary.
        Icollection<tvalue> Values {get;
        }//Returns Whether this dictionary contains a particular key.

        BOOL ContainsKey (TKey key);
        Adds a Key-value pair to the dictionary.

        void Add (TKey key, TValue value);
        Removes a particular key from the dictionary.

        BOOL Remove (TKey key);
    BOOL TryGetValue (TKey key, out TValue value);
 }

In the above interface and generic form, you can first see the definition of an indexer, with key as the index subscript, get the corresponding value. And through the source can see that key and value are ICollection types of a set of sets. And also defines some common methods of dictionary operation. Add, include judgment, remove, etc. These two interfaces are the base class for all dictionary data structures.

In a generic interface, you can also see that it inherits a KeyValuePair

==++==////Copyright (c) Microsoft Corporation.
All rights reserved. ==--==/*============================================================ * * * * * * * interface:keyvaluepair * * * * <OWN Er>[...]
</OWNER> * * * * * * purpose:generic key-value pair for dictionary enumerators. * * * * * ===========================================================*/namespace System.Collections.Generic {using Sys
    Tem

    Using System.Text;
    A keyvaluepair holds a key and a value from a dictionary. It is used by the ienumerable<t> implementation for both Idictionary<tkey, tvalue>//And Ireadonlydict
    Ionary<tkey, Tvalue>
        [Serializable] public struct Keyvaluepair<tkey, tvalue> {private TKey key;

        private TValue value;
            Public KeyValuePair (TKey key, TValue value) {this.key = key;
        This.value = value;
        The public TKey key {"Return" key;} } PubLic TValue value {get {return value;}
            public override string ToString () {StringBuilder s = stringbuildercache.acquire ();
            S.append (' [');
            if (Key!= null) {S.append (key.tostring ());
            } s.append (",");
            if (Value!= null) {S.append (value.tostring ());
            } s.append ('] ');
        return Stringbuildercache.getstringandrelease (s);
 }
    }
}

Next, take a rough look at the specific implementation of dictionary:

Namespace System.Collections.Generic {using System;
    Using System.Collections;
    Using System.Diagnostics;
    Using System.Diagnostics.Contracts;
    Using System.Runtime.Serialization;

    Using System.Security.Permissions;
    [DebuggerTypeProxy (typeof (Mscorlib_dictionarydebugview<,>))]
    [DebuggerDisplay ("Count = {count}")]
    [Serializable] [System.Runtime.InteropServices.ComVisible (false)] public class Dictionary<tkey,tvalue>: Idictionary<tkey , Tvalue>, IDictionary, Ireadonlydictionary<tkey, Tvalue>, ISerializable, Ideserializationcallback {pri    vate struct Entry {public int hashcode;        Lower bits of hash code,-1 if unused public int next;           Index of next entry,-1 if last public TKey key;         Key of entry public TValue value;
        Value of entry} private int[] buckets;
        Private entry[] entries;
private int count;        private int version;
        private int freelist;
        private int freecount;
        Private iequalitycomparer<tkey> comparer;
        Private keycollection keys;
        Private ValueCollection values;

        Private Object _syncroot;
        Constants for serialization Private Const String Versionname = "Version";  Private Const String Hashsizename = "Hashsize"; Must save buckets.
        Length Private Const String keyvaluepairsname = "Keyvaluepairs";

        Private Const String Comparername = "comparer"; Public Dictionary (): This (0, null) {} public Dictionary (int capacity): This (capacity, NULL) {} public Di Ctionary (iequalitycomparer<tkey> Comparer): This (0, comparer) {} public Dictionary (int capacity, IEQUALITYC Omparer<tkey> comparer) {if (capacity < 0) Throwhelper.throwargumentoutofrangeexception (exceptionarg
            ument.capacity); if (capacity > 0) Initialize (capacity); This.comparer = comparer?? Equalitycomparer<tkey>.
        Default; Public Dictionary (idictionary<tkey,tvalue> Dictionary): This (Dictionary, null) {} public diction ary (idictionary<tkey,tvalue> dictionary, iequalitycomparer<tkey> comparer): This dictionary!= L? Dictionary. count:0, comparer) {if (dictionary = null) {throwhelper.throwargumentnullexception (Except
            Ionargument.dictionary); foreach (keyvaluepair<tkey,tvalue> pair in dictionary) {ADD (pair. Key, pair.
            Value);

 } ...//slightly

This is the core of the basic dictionary class, in addition to this implementation class, the dictionary class and the SortedDictionary class, these two classes are in mscorlib and system two packages, logically sorteddictionary should be for the Dictionary class encapsulation, In which the data is stored _treeset by a two-fork tree structure. The implementation also involves the implementation of the tree structure and the implementation of the comparator, if further in-depth, you can directly refer to the source code:

        Public TValue This[tkey Key] {get {if (key = = null) {Throwhelp Er.                    
                Throwargumentnullexception (Exceptionargument.key); } Treeset<keyvaluepair<tkey, Tvalue>> Node node = _set.
                Findnode (New Keyvaluepair<tkey, tvalue> (key, Default (TValue));                    
                if (node = = null) {throwhelper.throwkeynotfoundexception (); Return node.
            Item.value; The set {if (key = = null) {throwhelper.throwargumentnullexception (exceptio
                Nargument.key); } Treeset<keyvaluepair<tkey, Tvalue>> Node node = _set.
                Findnode (New Keyvaluepair<tkey, tvalue> (key, Default (TValue)); if (node = null) {_set.                     ADD (New Keyvaluepair<tkey, tvalue> (key, value));   
                } else {node. Item = new Keyvaluepair<tkey, tvalue> (node.
                    Item.key, value); _set.
                Updateversion (); }}/*** is the implementation of the indexer above, and the following is the internal method of finding the tree node.
Method contains the implementation of a comparer.
            /Internal Virtual node Findnode (T Item) {node current = root; While (the current!= null) {int order = Comparer.compare (item, current.
                Item);
                if (order = = 0) {return current; else {current = (Order < 0)? Left:current.
                right;
        } return null;
 }

On C # collection _set Part _iset and Ihashset

From the above ordered dictionary set, which has a TREESET data structure, which can be extended by the set of related
//treeset inheritance Sortedset,sortedset inheritance iset,icollection, first understand the specific content of Iset
////below the source code reference. NET Framework 4.5
==++==////Copyright (c) Microsoft Corporation.
All rights reserved. ==--==/*============================================================ * * * * * * * * * interface:iset <OWNER>[. ...]
</OWNER> * * * * * Purpose:base interface for all generic sets. * * * * * ===========================================================*/namespace System.Collections.Generic {using Sys
    Tem


    Using System.Runtime.CompilerServices; <summary>///Generic Collection that guarantees the uniqueness of it elements, as defined///by some Comparer.
    It also supports basic set operations such as Union, intersection,///complement and Exclusive complement. </summary> public Interface iset<t>: icollection<t> {//add ITEM to the set, return TR    

        UE If added, False if duplicate new bool Add (T item); Transform this set to the its union and the ienumerable<t> other void Unionwith (IenumerabLe<t> other); Transform this set to its intersection to the ienumberable<t> other void Intersectwith (ienumerable<

        T> other); Transform This set so it contains no elements that are also into other void Exceptwith (ienumerable<t>)

        ; Transform This set so it contains elements initially in and in, but not both void Symmetricexceptwith (

        Ienumerable<t> other);

        Check If this set is a subset of the other bool IsSubsetOf (ienumerable<t>);

        Check If this set is a superset of the other bool Issupersetof (ienumerable<t>); Check If this set are a subset of other, but not the same as it bool IsProperSupersetOf (ienumerable<t> othe

        R); Check If this set are a superset of other, but not the same as it bool Ispropersubsetof (ienumerable<t> othe

        R); Check If this set has any elements in common with Other bool overlaps (ienumerable<t> other); Check If this set contains the same and the same elements as other bool Setequals (ienumerable<t> othe


    R); }

}

The above interface source can be seen Iset is the basic interface of all generic sets. It can be seen that it is directly inherited by ICollection and provides its own definition of behavior. It contains several distinct elements internally, and the elements are unordered.
In SortedSet, you can see that its interior is much more complex than iset, including the concrete implementation of its internal data storage. If you can see the source directly, you can see that its implementation is based on stack. And still use the binary tree to ensure that the elements of its internal data storage in an orderly state.
Next, look at the specific implementation of the set interface:

  public class hashset<t>: Icollection<t>, ISerializable, Ideserializationcallback, iset<t>

Specific details do not do in-depth, here the source code can be seen directly hashset inherited and Iset generic interface. HashSet is a disordered set that can remain unique. We can also think of hashset as a dictionary.

    public class Hashtable:idictionary, ISerializable, Ideserializationcallback, icloneable {
    //abbreviated

}

By its inheritance relationship, we can see that Hashtable is actually inheriting the Non-generic form of the Dictionary interface IDictionary as well as the serialization interface and the deserialized interface. And Hashtable is not generic, this and hashset,dictionary are not the same. The common HashMap in Java, in the early days of the construction of C # project, although a lot of reference to Java, but it seems that hashmap directly abandoned. So there was no such thing as Hashtable and HashMap. But there is the question of hashset,hashtable and dictionary that distinguishes such more dog blood.

Written in the last:
1. The recent exams have made me feel a deep sense of the weakness of underlying knowledge and theoretical principles in addition to these basic engineering knowledge. In the process of preparing the exam, the decision is to adjust the next 2 years of learning ideas.
2. In view of the importance of the paper when applying for a degree, a portion of the time will be devoted to the introductory synthesis of NLP related reading and paper tracking in the subject frontier technology.
3. In addition, as far as possible in the later theoretical study, the use of pure English materials for reading, writing and related work.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.