The difference between arrays, ArrayList, and list in C #

Source: Internet
Author: User

[Reference Bobwei's blog:https://www.cnblogs.com/BObwei/p/4869157.html]

In C #, Arraylist,list can store a set of objects, so what is the difference between these three?

Array

Arrays are the first to appear in C #. It is continuously stored in memory, so the index is fast and the assignment and modification elements are simple. You can use the offset address to access the element, the time complexity is O (1), you can use the binary lookup method to find the element, high efficiency.

  

String[] S=Newstring[3];// assignment s[0]=  "a"  ; S[1]= "b" ;s[2]= " c ";  modify S[1]=b1";           

Also, arrays have many drawbacks. The array is allocated on a contiguous data space, so the size must be determined when allocating space. The continuous space also leads to low storage efficiency, less efficiency in inserting and deleting elements, and trouble. If you want to add an element, you need to move a large number of elements, empty the space of an element in memory, and then put the added elements in it. Similarly, you want to delete an element, you need to move a large number of elements to fill the moved element.

And when we declare an array, we must also indicate the length of the array, the length of the array, the memory wasted, the array and the length too short, causing the data overflow error. So if we don't know the length of the array when we declare the array, it becomes tricky.

For these drawbacks of arrays, ArrayList objects are first provided in C # to overcome these drawbacks.

ArrayList

ArrayList is a dedicated class provided by the. Net Framework for data storage and retrieval, which is part of the namespace System.Collections. Its size is dynamically expanded and shrunk according to the data stored in it. Therefore, we do not need to specify the length of the ArrayList object when declaring it.

ArrayList inherits the IList interface, so it can be easily added, inserted, and removed from the data. For example:

ArrayList list =NewArrayList ();//New data list. ADD ("Abc"); list. ADD (123);//modifying Data list[2] =345;//Removes the data list. RemoveAt (0);//Insert Data list. Insert (0,"Hello World"); Gets the element valueObject value = Al[index];//Al is a ArrayList object, and it is generally necessary to convert value to type, for example: int n = (int) value;Set element value Al[index] = value;//Al is a ArrayList object, index must be less than CountAppend elementint Arraylist.add (Object value)//Returns the index of the added elementinserting elementsvoid Arraylist.insert (int index,ObjectValue) After the element is deleted, the subsequent element is moved, but the capacity does not change.void Arraylist.remove (Object obj)//Once in the past (index 0), find the first and the same element as objvoid Arraylist.removeat (int index)//Delete index corresponding elementvoid Arraylist.removerange (int index,int count)//Delete count elements starting at indexFind elementint Arraylist.indexof (Object value)//Looking back from the previous (index 0), returns the index of the first found element of the same as objint Arraylist.indexof (Object value,int StartIndex) int Arraylist.indexof (object value, int StartIndex, int count) int Arraylist.lastindexof (object value) // lookup from backward forward (index 0), returns the index of the first found element of the same as obj int arraylist.lastindexof (object value, int StartIndex) Span style= "COLOR: #0000ff" >int arraylist.lastindexof (object value, int StartIndex, int count)        

From the above example, ArrayList seems to solve all the shortcomings in the array, then it should be perfect, why the list after the c#2.0?

Or from the example above, in list, we not only inserted the string "abc", but also inserted the number 123. This allows the insertion of different types of data in the ArrayList. Because ArrayList will handle all the data inserted into it as an object type. Thus, when we use the data in ArrayList to handle the problem, it is possible to report a type mismatch error, that is, ArrayList is not type-safe. Even though we are guaranteed to be careful when inserting data, we have inserted the same type of data, but in use, we also need to convert them to the corresponding primitive type to handle. This is the case of boxing and unpacking operation, will bring a lot of performance loss.

Interspersed with the concept of boxing and unpacking:

In simple terms:

Boxing: is to package data of a value type into an instance of a reference type

For example, the value 123 of the int type is assigned to the object o

int i=123;  Object o= (object) i;   

Unpacking: Extracting value types from reference data

For example, assigning the value of the object o to the variable I of type int

Object o=123;  int i= (int) o;   

The process of packing and unpacking is very lossy.

Generic List

It is because ArrayList has the disadvantage of unsafe type and packing unpacking, so the concept of generics appears after c#2.0. The list class is a generic equivalent class of the ArrayList class. Most of its usage is similar to ArrayList, because the list class inherits the IList interface as well. The key difference is that when declaring a list collection, we also need to declare the object type for the data in the list collection.

list<New list<int>();  new data list. ADD (123);  Modify Data list[345;  removes the data list. RemoveAt (0);             

In the example above, if we insert the string character "Hello World" into the list collection, the IDE will report an error and cannot be compiled. This avoids the previously mentioned type-safety issues and the performance issues of packing unboxing.

Console.WriteLine ("List Test:");//Declares a List list< of an integral typeInt> lstest =New list<Int>(); Lstest.add (7); Lstest.add (5); Lstest.add (1); Lstest.add (3);String strtest="";//list sort lstest.sort (); //list traversal foreach (int i in Lstest) strtest+=i. ToString () + "" ; // output console.write after formatting ( String. Format ( "out:{0} ncount:{1}n  ",strtest,lstest.count)); // reads the next key to let the screen display data Console.readkey ();     

The results are as follows

Program code list test:out:7 Count:4  

The difference between arrays, ArrayList, and list 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.