Many non-generic collection classes we use mainly include the arraylist class and the hashtable class. We often use hashtable to store the information to be written to the database or returned. In this case, we need to constantly convert the data types, increasing the burden of system packing and unpacking. At 14:31:45, for example, you can use dictionary <string, int> to store your shopping cart information (product name, number of items) on an e-commerce website, without any type conversion.
1. arrays are fixed in size and cannot be scaled. Although the generic method system. array. Resize can reset the array size,
However, this method re-creates an array with the new size and initializes it with elements of the old array. Then the previous array will be discarded! The set is variable-length.
2. the array must declare the element type. The element type of the Collection class is object.
3. the read-only array cannot be declared for readable and writable arrays. The Collection class can provide the readonly method to use the set in read-only mode.
4. the array must have an integer subscript to access specific elements. However, such subscript is not very useful in many cases. The set is also a data list, but it does not use subscript access.
Most of the time there is a set of custom subscript types, which does not support subscript access for queues and stacks!
1. Array
Int [] intarray1;
// Initialize the declared one-dimensional array
Intarray1 = new int [3];
Intarray1 = new int [3] {1, 2, 3 };
Intarray1 = new int [] {1, 2, 3 };
2. The arraylist class object is designed as a dynamic array type, and its capacity will be expanded as needed
Method
1: Add () adds an element to the array,
2: Remove () deletes an element in the array.
3: removeat (int I) deletes the elements whose index value is I in the array.
4: reverse () reverses the elements of the array.
5: Sort () arranges the elements of the array in ascending order.
6: Clone () to copy an array
Using system; using system. collections. generic; using system. text; using system. collections; namespace consoleapplication1 {class program {static void main (string [] ARGs) {arraylist Al = new arraylist (); Al. add (100); // Add foreach (INT number in New int [6] {9, 3, 7, 2, 4, 8}) {Al. add (number); // Add group method 1 // clear moon} int [] number2 = new int [2] {11,12}; Al. addrange (number2); // Add method 2. remove (3 );// Remove Al with a value of 3. removeat (3); // remove 3rd arraylist Al = new arraylist (Al. getrange (1, 3); // The New arraylist takes only a portion of the old arraylist as the console. writeline ("Traversal method 1:"); foreach (int I in Al) // do not forcibly convert {console. writeline (I); // Traversal method 1} console. writeline ("Traversal method 2:"); For (INT I = 0; I! = Al2.count; I ++) // The array is length {int number = (INT) al [I]; // The console must be forcibly converted. writeline (number); // Traversal method 2 }}}}
3. List
List of strong types of objects that can be accessed through indexes. Provides methods for searching, sorting, and operating the list. When you decide whether to use the list or the arraylist class (the two have similar functions, remember that the List class performs better and is type-safe in most cases. If the type T of the List class is referenced, the behavior of the two classes is identical. However, if you use value type T, you need to consider implementation and packing.
If the value type T is used, the compiler will generate a list class for this value type. This means that you can use this element without packing the list element of the list object. After about 500 list elements are created, the memory saved by packing the list elements is greater than the memory used to generate this class.
// Declare a list object and add only the string parameter list <string> names = new list <string> (); names. add ("Qiao Feng"); names. add ("Ouyang Feng"); names. add ("Bee"); // traverse list foreach (string name in names) {console. writeline (name);} // Insert the element names to the list. insert (2, "Zhang Sanfeng"); // remove the specified element names. remove ("Bee ");
4. Dictionary
A set of keys and values. The order in which dictionary traverses the output is the order of addition, which is different from that in hashtable.
Dictionary <string, string> mydic = new dictionary <string, string> (); mydic. add ("AAA", "111"); mydic. add ("BBB", "222"); mydic. add ("CCC", "333"); mydic. add ("DDD", "444"); // if an existing key is added, the add method throws an exception. Try {mydic. add ("DDD", "DDD");} catch (argumentexception ex) {console. writeline ("this key already exists:" + ex. message);} // The containskey () method is used to determine whether the key exists if (! Mydic. containskey ("DDD") {mydic. add ("DDD", "DDD");} else {console. writeline ("this key already exists:");} // when the index is used for negative values, if the key already exists, the key value of the existing key is modified, and does not throw an exception. mydic ["DDD"] = "DDD"; mydic ["eee"] = "555"; // when the indexer is used for value, if the key does not exist, an exception will be thrown. Try {console. writeline ("nonexistent key" "fff" "has the key value:" + mydic ["fff"]);} catch (keynotfoundexception ex) {console. writeline ("the key is not found and an exception is thrown:" + ex. message );}
// The method to solve the above exception is to use contarnskey () to determine if a key exists. If you need to calculate the key value frequently, it is best to use trygetvalue to obtain the corresponding key value in the set.
String value = ""; if (mydic. trygetvalue ("fff", out value) {console. writeline ("nonexistent key" "fff" "key value:" + value);} else {console. writeline ("the corresponding key value is not found");} // The following uses foreach to traverse the key-Value Pair // generic struct to store the key-Value Pair foreach (keyvaluepair <string, string> kVp in mydic) {console. writeline ("Key = {0}, value = {1}", kVp. key, kVp. value);} // obtain the value set foreach (string s in mydic. values) {console. writeline ("value = {0}", S) ;}// obtain a dictionary <string, string>. valuecollection values = mydic. values; foreach (string s in values) {console. writeline ("value = {0}", S );}
Common attributes and methods are as follows:
Common attributes
Attribute description
Comparer
Obtain the iequalitycomparer used to determine whether the keys in the dictionary are equal.
Count
Obtains the number of key/value pairs contained in a dictionary.
Item
Gets or sets the value associated with the specified key.
Keys
Obtains a set of keys in a dictionary.
Values
Obtains a set of values in a dictionary.
Common Methods
Method description
Add
Adds the specified key and value to the dictionary.
Clear
Remove all keys and values from dictionary.
Containskey
Determines whether a dictionary contains the specified key.
Containsvalue
Determines whether a dictionary contains a specific value.
Equals
Overloaded. Determine whether the two object instances are equal. (Inherit from object .)
Getenumerator
Returns the number of enumerations that access the dictionary cyclically.
Gethashcode
Used as a hash function of a specific type. Gethashcode is suitableAlgorithmAnd data structures (such as hash tables. (Inherit from object .)
Getobjectdata
Implement the system. runtime. serialization. iserializable interface and return the data required to serialize the dictionary instance.
GetType
Obtain the type of the current instance. (Inherit from object .)
Ondeserialization
Implement the system. runtime. serialization. iserializable interface and trigger a deserialization event after deserialization.
Referenceequals
Determine whether the specified object instance is the same. (Inherit from object .)
Remove
Removes the value of the specified key from dictionary.
Tostring
Returns the string of the current object. (Inherit from object .)
Trygetvalue
Obtains the value associated with the specified key.
5. sortedlist class
Similar to a hash table, the difference is that the key array in sortedlist has sorted
// Sortedlist system. collections. sortedlist list = new system. collections. sortedlist (); list. add ("key2", 2); List. add ("key1", 1); For (INT I = 0; I <list. count; I ++) {system. console. writeline (list. getkey (I ));}
6. hashtable class
Hash table, name-value pair. Similar to a dictionary (more powerful than an array ). The hash table is optimized, and the objects accessing the underlying object are first hashed. If any type of key value is used to access the element, it is faster than other sets.
The gethashcode () method returns an int type data. The value of this key is used to generate the int type data. The hash table returns an index after obtaining this value, indicating the location where the data items with the given hash are stored in the dictionary.
Hashtable and dictionary <K, V> types
1: single threadProgramIt is recommended to use dictionary. It has the wildcard advantage, and the reading speed is faster, and the capacity utilization is more adequate.
2: hashtable is recommended in multi-threaded programs. The default hashtable allows single-threaded writing and multi-threaded reading. For hashtable, the synchronized () method can be further called to obtain a completely thread-safe type. dictionary is NOT thread-safe and must be manually protected using the lock statement, greatly reducing the efficiency.
3: dictionary has the ability to sort data by insertion Order (Note: however, when the remove () function is called to delete a node, the order is disrupted ), therefore, it is convenient to use a dictionary to reflect the order.
The key/value in hashtable is of the object type and is composed of buckets containing collection elements. A bucket is a virtual sub-group of each element in hashtable. Compared with searching and searching in most sets, a bucket can make searching and searching easier. Each bucket is associated with a hashCodeAssociation. The hash code is generated using a hash function and is based on the key of this element. The advantage of hashtable lies in its indexing method, which is very fast. If any type of key value is used to access the element, it is faster than other sets, especially when the data volume is very large, the efficiency difference is particularly large.
Hashtable applications include Object Caching, substitution of tree recursive algorithms, and various scenarios that require efficiency improvement.
// hashtable Sample System. collections. hashtable ht = new system. collections. hashtable (); // -- be careful: Keys can't be duplicated, and can't be null ---- ht. add (1, "apple"); ht. add (2, "banana"); ht. add (3, "orange"); // Modify item value: If (HT. containskey (1) HT [1] = "applebad"; // the following code will return NULL ovalue, no exception object ovalue = HT [5]; // traversal 1: foreach (dictionaryentry de in HT) {console. writeline (de. key); console. writeline (de. value);} // traversal 2: system. collections. idictionaryenumerator d = ht. getenumerator (); While (D. movenext () {console. writeline ("key: {0} value: {1}", D. entry. key, D. entry. value);} // clear items ht. clear ();
Dictionary is similar to hashtable in internal implementation, but the former does not require packing and unpacking, and the efficiency is slightly higher.
// Dictionary Sample System. collections. generic. dictionary <int, string> fruits = new system. collections. generic. dictionary <int, string> (); fruits. add (1, "apple"); fruits. add (2, "banana"); fruits. add (3, "orange"); foreach (int I in fruits. keys) {console. writeline ("key: {0} value: {1}", I, fruits);} If (fruits. containskey (1) {console. writeline ("Contain this key. ");}
Hashtable is optimized, and objects that access the underlying object are first hashed, so internal hash is unordered, which ensures high efficiency. That is to say, the output is not in the order of initial addition, the order in which dictionary traverses the output is the order of addition, which is different from that in hashtable. To sort hashtable output, you can only implement it by yourself:
// Hashtable sorting system. collections. arraylist akeys = new system. collections. arraylist (HT. keys); // from hashtable akeys. sort (); // sort by leading letter foreach (string skey in akeys) {console. write (skey + ":"); console. writeline (HT [skey]);}
Hashtable and thread security:
To ensure thread synchronization access security in the case of multiple threads, Microsoft provides hashtable for Automatic Thread Synchronization:
If hashtable allows concurrent reads but can only be written by one thread, create a hashtable instance as follows:
// Thread safe hashtable
System. Collections. hashtable htsyn = system. Collections. hashtable. synchronized (new system. Collections. hashtable ());
In this way, if multiple threads attempt to write items in hashtable concurrently, only one thread can write at the same time, and the rest will be blocked; the read threads will not be affected.
Another method is to use the lock statement, but it is not hashtable but its syncroot to be locked. Although this method is not recommended, the effect is the same becauseSource codeIs implemented as follows:
// Thread safeprivate static system. collections. hashtable htcache = new system. collections. hashtable (); public static void accesscache () {lock (htcache. syncroot) {htcache. add ("key", "value"); // be careful: don't use foreach to operation on the whole collection // otherwise the collection won't be locked correctly even though indicated locked // -- by msdn} // is equivalent (lock is equivalent to monitor. enter and exit () public static void accesscache () {system. threading. monitor. enter (htcache. syncroot); try {/* critical section */htcache. add ("key", "value"); // be careful: don't use foreach to operation on the whole collection // otherwise the collection won't be locked correctly even though indicated locked // -- by msdn} finally {system. threading. monitor. exit (htcache. syncroot );}}
7. Stack
Stack. Push method into the stack, pop method out of the stack.
System. collections. stack stack = new system. collections. stack (); stack. push (1); stack. push (2); system. console. writeline (stack. peek (); While (stack. count> 0) {system. console. writeline (stack. pop ();} 8. queue class, first-in-first-out. The enqueue method is used to enter the queue, and the dequeue method is used to output the queue. System. collections. queue queue = new system. collections. queue (); queue. enqueue (1); queue. enqueue (2); system. console. writeline (queue. peek (); While (queue. count> 0) {system. console. writeline (queue. dequeue ());}
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/snlei/archive/2009/02/26/3939206.aspx