[Translation] C # data structures and algorithms-Chapter 2 (Part2)

Source: Internet
Author: User

ArrayList class

Static arrays are not very useful because the length of an array cannot be known in advance or may change in the life cycle of a program. One solution to this problem is to use an array in the program that can dynamically adjust the size when the default storage space is exceeded. This type of array is called ArrayList and is located under System. Collections of the. Net class library.

An ArrayList object has a Capacity attribute to store its size. The initial value of this attribute is 16. When the number of elements in an ArrayList reaches this limit, ArrayList automatically adds the storage space of the 16 elements represented by the Capacity attribute. Using ArrayList is more efficient than using the standard array ReDim method when the number of array elements may increase.

As we discussed in chapter 1, an ArrayList object stores objects of the object type. If you need to store data in a strongly typed manner, you need to use standard arrays or other data structures.

Members of the ArrayList class

The ArrayList class contains the required methods and attributes so that you can easily use ArrayList. The following is a list of the most common methods and attributes.

Add (): Add an element to ArrayList.

AddRange (): adds a set of elements to the end of ArrayList.

Capacity: number of elements that can be saved by ArrayList by default

Clear (): removes all elements from the ArrayList.

Contains (): determines whether ArrayList Contains a specified item.

CopyTo (): copy an ArrayList or a part of it to another array.

Count: returns the number of current elements in the ArrayList.

GetEnumerator (): returns an enumerator to iterate the ArrayList.

GetRange (): Get a subset of ArrayList as a new ArrayList

IndexOf (): returns the first matching index of the specified project.

Insert (): Insert an element to the specified index of ArrayList.

InsertRange (): a set of elements inserted at the specified position of ArrayList

Item: Attribute-elements at the specified index

Remove (): removes the first match of a specified project.

RemoveAt (): removes the elements at the specified index.

Reserve (): sorts the elements in the ArrayList in reverse order.

Sort (): arrange the elements in ArrayList alphabetically

ToArray (): copy the elements of ArrayList to an array.

TrimToSize (): sets the Capacity attribute to the actual number of elements in the ArrayList.

Use the ArrayList class

ArrayList does not use standard arrays. Generally, a project is added to the ArrayList using the Add method. An element needs to be added to a special position unless otherwise specified. In this case, the Insert method is used. In this section, let's take a look at how to use the zero-zero total method in ArrayList.

First, we need to declare an object of this class as follows:

ArrayList grades = new ArrayList ();

Note that the constructor is called in the Declaration. If an ArrayList does not use constructors, the object is unavailable in subsequent program statements.

Use the Add method to Add an object to the ArrayList. This method accepts a parameter-an object to be added to the ArrayList. At the same time, this method also returns an integer indicating the position where the element is added, although this value is not commonly used in the program. The following are some examples:

Grades. Add (100 );

Grades. Add (84 );

Int position;

Position = grades. Add (77 );

Console. WriteLine ("The grade 77 was added at position:" + position );

Objects in the ArrayList can be displayed using a foreach loop. ArrayList has a built-in enumerator to manage the iterations of all objects in ArrayList, one at a time. The following code snippet shows how to use a foreach loop in ArrayList.

Int total = 0;

Double average = 0.0;

Foreach (Object grade in grades)

Total + = (int) grade;

Average = total/grades. Count;

Console. WriteLine ("The average grade is:" + average );

If you want to add an element at the specified position of ArrayList, you can use the Insert method. This method accepts two parameters: the position of the element to be inserted and the element to be inserted. The following code snippet inserts two scores at a specified position to maintain the order of the ArrayList objects:

Grades. Insert (1, 99 );

Grades. Insert (3, 80 );

You can call the Capacity attribute to view the current Capacity of an ArrayList, and use the Count attribute to view the current number of elements in an ArrayList:

Console. WriteLine ("The current capacity of grades is:" + grades. Capacity );

Console. WriteLine ("The number of grades in grades is:" + grades. Count );

There are several ways to remove items from an array. If you know the item you want to Remove but do not know its location, you can use the Remove Method. This method only accepts one parameter-the object to be removed by ArrayList. If the object exists in the ArrayList, it is removed. If the object is no longer in the array, no processing will be performed. When a Remove-like method is called, it is usually put in an If-Then statement for calling, and the method (such as the Contains method) is used to verify whether the object exists in ArrayList. The following is a sample code segment for this process:

If (grades. Contains (54 ))

Grades. Remove (54 );

Else

Console. Write ("Object not in ArrayList .");

If you know the index of the object you want to remove, you can use the RemoveAt method. This method accepts a parameter-the index of the object to be removed. The only exception that will be caused when you pass the method an invalid index. The method works as follows:

Grades. RemoveAt (2 );

You can call the IndexOf method of ArrayList to determine the location of an object. This method accepts a parameter-the object to be searched, and returns the position of the object in the ArrayList. If the object is not in the ArrayList, this method returns-1. The following code snippet demonstrates the combination of the IndexOf method and the RemoveAt method:

Int pos;

Pos = grades. IndexOf (70 );

Grades. RemoveAt (pos );

In addition to adding a single object to the ArrayList, you can also add a range object. These objects must be stored in an object that implements the ICollection interface. This means that the object can be stored in an array, a set, or even another ArrayList.

There are two different ways to add objects in a range to the ArrayList, namely the AddRange method and the InsertRange method. The AddRange method adds a range object to the end of the ArrayList. The InsertRange method adds a range object to the specified position in the ArrayList.

The following program demonstrates the use of these two methods:

Using System;

Using System. Collections;

Class class1 {

Static void Main ()

{

ArrayList names = new ArrayList ();

Names. Add ("Mike ");

Names. Add ("Beata ");

Names. Add ("Raymond ");

Names. Add ("Bernica ");

Names. Add ("Jennifer ");

Console. WriteLine ("The original list of names :");

Foreach (Object name in names)

Console. WriteLine (name );

Console. WriteLine ();

 

String [] newNames = new string [] {"David", "Michael "};

ArrayList moreNames = new ArrayList ();

MoreNames. Add ("Terrill ");

MoreNames. Add ("Donnie ");

MoreNames. Add ("Mayo ");

MoreNames. Add ("Clayton ");

MoreNames. Add ("Alisa ");

Names. InsertRange (0, newNames );

Names. AddRange (moreNames );

Console. WriteLine ("The new list of names :");

Foreach (Object name in names)

Console. WriteLine (name );

}

}

The output of this program is as follows:

David Michael Mike Bernica Beata Raymond Jennifer Terrill Donnie Mayo Clayton Alisa

Because the specified index is 0, the first two names are added to the starting position of the ArrayList, because the names after the AddRange method are added to the end.

The other two Programmers think that the ToArray and GetRange methods are useful. The GetRange method returns an object of the specified range in an ArrayList to another ArrayList. The ToArray method copies all elements in the ArrayList to an array. First, let's take a look at the GetRange method.

The GetRange method accepts two parameters: the starting index and the number of elements to be retrieved from the ArrayList. The GetRange method is non-destructive, that is, it only copies objects from the original ArrayList to the new ArrayList. The following example shows how this method works. It uses the previous program:

ArrayList someNames = new ArrayList ();

SomeNames = names. GetRange (2, 4 );

Console. WriteLine ("someNames sub-ArrayList :");

Foreach (Object name in someNames)

Console. WriteLine (name );

The output of the program fragment is:

Mike Bernica Beata Raymond

The ToArray method allows you to easily move the content in the ArrayList to a standard array. The main reason you will use the ToArray method is that you can use arrays to get faster access speed.

The ToArray method does not accept parameters and returns the elements in the ArrayList to an array. The following example shows how to use this method:

Object [] arrNames;

ArrNames = names. ToArray ();

Console. WriteLine ("Names from an array :");

For (int I = 0; I <= arrNames. GetUpperBound (0); I ++)

Console. WriteLine (arrNames [I]);

The last part of the code snippet proves that the elements in the ArrayList have actually been stored in the arrNames

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.