Differences between dictionary, arraylist, hashtable and array in C #

Source: Internet
Author: User
Tags array definition

C # collection class array arraylist list hashtable dictionary stack queue
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!

Arraylist is a complex version of an array. The arraylist class provides some functions that are provided in most collections classes but not in the array class. For example:

The array capacity is fixed, and the arraylist capacity is automatically expanded as needed. If the value of the arraylist. Capacity attribute is changed, memory reallocation and element replication are performed automatically.
Arraylist allows you to add, insert, or remove a range of elements. In array, you can only get or set the value of one element at a time.
Using synchronized, you can easily create a synchronization version of arraylist. Array will keep it until the user achieves synchronization.
Arraylist provides a method to return read-only and fixed-size packages to a set. Array does not.
On the other hand, array provides some flexibility that arraylist does not have. For example:

You can set the lower limit of array, but the lower limit of arraylist is always zero.
Array can have multiple dimensions, while arraylist is always one-dimensional.
Array of a specific type (excluding objects) has better performance than arraylist. This is because the elements of arraylist belong to the object type. Therefore, when storing or retrieving value types, binning and unboxing are usually generated.
In most cases, an array can be replaced by arraylist. It is easier to use and generally has the same performance as an array of the object type.

Array is located in the system namespace; arraylist is located in the system. Collections namespace.

// 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 };

// 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

// Arraylist dynamic array definition assignment output arraylist can be dynamically assigned with different types of values without a specified dimension
Arraylist arraylist1 = new arraylist ();
Arraylist1.
Arraylist1.add ("");
Arraylist1.add (1 );
Arraylist1.add ("B ");
Response. Write (arraylist1 [1]);

// Array class all array base class definition assignment output array capacity is fixed first specify the size in the assignment
Array arraylist2 = array. createinstance (typeof (string), 6 );
Arraylist2.setvalue ("A", 0 );
Arraylist2.setvalue ("B", 1 );
Response. Write (arraylist2.getvalue (1 ));

// Array definition value assignment output first specifies the size in the value assignment
String [] arraylist;
Arraylist = new string [] {"A", "B", "C", "D "};
Arraylist [0] = "ABCDE ";
Arraylist [2] = "1234 ";

Arraylist. setvalue ("DD", 3 );
Response. Write (arraylist [0]);

// Hash table
Hashtable abc = new hashtable ();
ABC. Add ("1", "34 ");
If (ABC. Contains ("1 "))
{
Response. Write (ABC ["1"]);
}
// Declare a two-dimensional array

Int [,] cells = int [3, 3];

// Initialize a two-dimensional integer Array

Int [,] cells = {1, 0, 2}, {1, 2}, {1, 2 }};

// List
List of strong types of objects that can be accessed through indexes. Provides methods for searching, sorting, and operating the list.
When deciding whether to use the list or the arraylist class (both 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 actions of the two classes are 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 this element can be used without packing the list element of the list object, and about 500 lists are created.

After the elements, the memory saved by packing the list elements will be greater than the memory used to generate the class.

// 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.

// Sortedlist class
Similar to a hash table, the difference is that the key array in sortedlist has sorted

// 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.

// Stack class
Stack. Push method into the stack, pop method out of the stack.

Queue class
Queue, first-in-first-out. The enqueue method is used to enter the queue, and the dequeue method is used to output the queue.

-------------------------------------------------------------

// Dictionary
System. Collections. dictionaryentry DIC = new system. Collections. dictionaryentry ("key1", "value1 ");

Dictionary <int, string> fruit = new dictionary <int, string> ();

// Adding the duplicate key will cause an exception.
Fruit. Add (1, "apple ");
Fruit. Add (2, "orange ");
Fruit. Add (3, "banana ");
Fruit. Add (4, "pineapple ");

// Because generics are introduced, object-to-int conversion is not required after the key is taken out, and the set of values is the same.
Foreach (int I in fruit. Keys)
{
Console. writeline ("key: {0} value: {1}", I, fruit );
}
// Delete the specified key and Value
Fruit. Remove (1 );
// Determine whether the specified key is included
If (fruit. containskey (1 ))
{
Console. writeline ("include this key ");
}
// Clear all objects in the Set
Fruit. Clear ();
}

// Arraylist
System. Collections. arraylist list = new system. Collections. arraylist ();
List. Add (1 );
List. Add (2 );
For (INT I = 0; I <list. Count; I ++)
{
System. Console. writeline (list [I]);
}

// List
// 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 the list
Foreach (string name in names)
{
Console. writeline (name );
}
// Insert an element to the list
Names. insert (2, "Zhang Sanfeng ");
// Remove the specified Element
Names. Remove ("Bee ");

// Hashtable
System. Collections. hashtable table = new system. Collections. hashtable ();
Table. Add ("Table1", 1 );
Table. Add ("Table2", 2 );
System. Collections. idictionaryenumerator d = table. getenumerator ();
While (D. movenext ())
{
System. Console. writeline (D. Entry. Key );
}

// 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 ());
}

// 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 ));
}

// 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 ());
}

Share:
  • Previous Article: dictionary, arraylist, hashtable and array in C #
Related Article

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.