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

Source: Internet
Author: User

Arraylist class

Because the length of an array cannot be known in advance or may beProgramStatic array is not very useful. 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:

ArraylistGrades =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 );

IntPosition;

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 followingCodeThe snippet shows how to use a foreach loop in the arraylist.

IntTotal = 0;

DoubleAverage = 0.0;

Foreach(ObjectGradeInGrades)

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:

IntPos;

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:

UsingSystem;

UsingSystem. collections;

Class Class1{

Static VoidMain ()

{

ArraylistNames =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(ObjectNameInNames)

Console. Writeline (name );

Console. Writeline ();

 

String[] Newnames =New String[] {"David","Michael"};

ArraylistMorenames =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(ObjectNameInNames)

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:

ArraylistSomenames =New Arraylist();

Somenames = names. getrange (2, 4 );

Console. Writeline ("Somenames sub-arraylist :");

Foreach(ObjectNameInSomenames)

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(IntI = 0; I <= arrnames. getupperbound (0); I ++)

Console. Writeline (arrnames [I]);

The last part of the code snippet proves that the elements in the arraylist are actually stored in the array of arrnames.

 

Summary

Arrays are the most common data structures in computer programming. Almost all computer languages have built-in support for arrays of various forms.

For many programs, arrays are the easiest and most efficient data structures to implement. Arrays are useful when you need to directly access an element located at the back of your dataset.

. NET Framework introduces a new type of array called arraylist. Arraylist has many array features, but it is more powerful, because they can be adjusted when the maximum capacity is reached. Arraylist also has some practical methods, such as executing insert, declaration, and search. Because C # does not allow the image in VB. net dynamically adjusts the size of an array, so when you process a storage that cannot predict the number of projects in advance, arraylist is a useful data structure.

 

Contact

1. Design and implement a class so that instructors can track scores of a course. This includes the calculation of average score, highest score, and lowest score. Write a program to test the implementation of your class.

2. Modify the class in contact 1 so that it can record the scores of multiple courses. Write a program to test your implementation.

3. Use arraylist to override contact 1. Write a program to test your implementation, and use the timing class to compare its performance with the array of contact 1.

4. Design and implement a class and use arrays to simulate the behavior of the arraylist class. Implement as many methods as possible in arraylist. Compile a program to test your class.

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.