[Translation] C # data structures and algorithms-Chapter 2 (Part1) Chapter 2 Arrays and ArrayLists

Source: Internet
Author: User

Chapter 2 Arrays and ArrayLists

Arrays are the most common data structures that appear in almost all programming languages. Using data in C # is essentially creating an Array object of the System. Array type. The System. Array class is composed of all arrays.AbstractionIt provides a series of methods to complete tasks that programmers have to manually implement in the past, such as sorting and searching.

An interesting alternative to arrays in C # Is the ArrayList class. ArrayList is an array that can automatically add buckets as needed. If you cannot accurately determine the final size of an array or the size of an array changes many times in the life cycle of the program, arraylist is a better choice than array.

In this chapter, we will quickly browse the basic use of arrays in C #, and then turn to a more advanced topic, including copying and cloning ArrayList objects, test quality and static methods for using them.

Array Basics

An array is an index-based set of data. Arrays can be both built-in and custom types. In fact, it is possible to regard the data in the array as an object that is the simplest. Data in C # is also an object, because they inherit from the System. Array class. Since the Array is an instance of the System. Array class, you can use the methods and attributes of the System. Array class when using arrays.

Declare and initialize an array

The array uses the following syntax declaration:

Type [] array-name;

Type is the data type of an array element, for example:

String[] Names;

The second row is required. It is used to initialize the Array (because it is a System. Array object) and determine the size of the Array. The following code initializes the declared names Array:

Names =New String[10];

And Reserved10Memory space of strings.

When necessary, you can merge the two statements into one row as follows:

String[] Names =New String[10];

Sometimes you want to put the declaration, initialization, and assignment Array Operations in a statement. in C #, you can complete the operation by initializing the list.

Int[] Numbers =New Int[] {1, 2, 3, 4, 5 };

The list of numbers, called the initialization list, is placed between a pair of curly braces and separated by commas. When using this technique to declare an array, you do not need to specify the number of elements. The Compiler deduce this value from the number of items in the initialization list.

Set and access array elements

Elements stored in the Array can be accessed directly or the SetValue method of the Array class can be called. Directly access the array elements at the specified position through the index on the left of the value assignment statement.

Names [2] ="Raymond";

Sales [19] = 23123;

The SetValue method provides a more object-oriented way to set the value of an array element. This method accepts two parameters, one index value and one element value.

Names. SetValue ("Raymond", 2 );

Sales. SetValue (23123, 19 );

Array elements can be accessed either through indexes or through the GetValue method. The GetValue method accepts a single parameter-an index value.

MyName = names [2];

MonthSales = (Int) Sales. GetValue (19 );

It is common to use a for loop to traverse the elements of an array. There are two errors that programmers often make when writing loop statements. One is the upper limit of hard-coded loops (this is an error because if the array is dynamic, its upper limit will change ). Another error is the upper limit of the iteration loop that calls a function to access each loop.

For(IntI = 0; I <= sales. GetUpperBound (0); I ++)

TotalSales = totalSales + sales [I];

Methods and attributes for retrieving array metadata

The Array class provides several attributes to check the metadata of an Array.

  • Length: returns the number of all elements of all dimensions in the array.
  • GetLength: returns the number of elements in the specified dimension of the array.
  • Rank: returns the dimension of the array.
  • GetType: Type of the current array instance.

The Length attribute is used to count the number of elements in a multi-dimensional array. It returns the exact number of elements in the array. In addition, you can use the GetUpperBound method to get the number of elements in the array by adding 1 to the value.

Length returns the total number of elements in the array. The GetLength method counts the number of elements in a single dimension in the array. This method is used together with the Rank attribute to adjust the size of the array without the risk of data loss at runtime. This technique will be discussed later in this chapter.

The GetType method is used to specify the data type of an array when you are not sure about the array type. For example, if you pass an array as a parameter to a method. In the following code snippet, a Type variable is created. You can use its IsArray method to determine whether an object is an array. If the object is an array, the Code returns the Data Type of the array.

Int[] Numbers;

Numbers =New Int[] {0, 1, 2, 3, 4 ,};

TypeArrayType = numbers. GetType ();

If(ArrayType. IsArray)

Console. WriteLine ("The array type is: {0 }", ArrayType );

Else

Console. WriteLine ("Not an array");

Console. Read ();

The GetType method not only returns the array type, but also lets us know that the object is essentially an array. The output of the above Code is as follows:

The array type is: System. Int32 []

Square brackets indicate that the object is an array. Pay attention to the format used when displaying data types. We have to do this because we cannot convert the Type data to a string to connect to the end of the string to be displayed.

Multi-dimensional array

So far, we have only discussed one array. In C #, Arrays can be up to 32 dimensions, although arrays larger than three dimensions are rare (and confusing ).

To declare a multi-dimensional array, specify the upper bound of each dimension of the array. To declare a two-dimensional array:

Int[,] Grades =New Int[4, 5];

Declares an array consisting of four rows and five columns of elements. A two-dimensional array is often used as a modeling matrix. You can declare a multi-dimensional array without specifying the dimension bounds. To do this, you can use a comma to specify the number of dimensions. For example:

Double[,] Sales;

Declares a two-dimensional array, and vice versa:

Double[,] Sales;

Declares a 3D array. When you declare an array without providing the upper bound of a dimension, you need to use the bounded value to define an array later:

Sales =New Double[4, 5];

Multi-dimensional array can be completed by using the initialization list

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.