Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
27
Добавлен:
25.03.2016
Размер:
14 Мб
Скачать
☆

192 Part II Understanding the C# Language

The second thing you need to do is set the values inside the new array to the same values as the original array. You could do this by using a for statement, as shown in this example:

int[] pins = { 9, 3, 7, 2 }; int[] copy = new int[pins.Length];

for (int i = 0; i < copy.Length; i++)

{

copy[i] = pins[i];

}

Copying an array is actually a common requirement of many applications—so much so that the System.Array class provides some useful methods that you can employ to copy an array rather than writing your own code. For example, the CopyTo method copies the contents of

one array into another array given a specified starting index:

int[] pins = { 9, 3, 7, 2 }; int[] copy = new int[pins.Length]; pins.CopyTo(copy, 0);

Another way to copy the values is to use the System.Array static method named Copy. As with CopyTo, you must initialize the target array before calling Copy:

int[] pins = { 9, 3, 7, 2 }; int[] copy = new int[pins.Length];

Array.Copy(pins, copy, copy.Length);

Yet another alternative is to use the System.Array instance method named Clone. You can call this method to create an entire array and copy it in one action:

int[] pins = { 9, 3, 7, 2 }; int[] copy = (int[])pins.Clone();

Note The Clone method actually returns an object, which is why you must cast it to an array of

the appropriate type when you use it. Furthermore, all four ways of copying shown earlier create a shallow copy of an array—if the elements in the array being copied contain references, the for

loop as coded and the three preceding methods simply copy the references rather than the objects being referred to. After copying, both arrays refer to the same set of objects. If you need to create a deep copy of such an array, you must use appropriate code in a for loop.

What Are Collection Classes?

Arrays are useful, but they have their limitations. Fortunately, arrays are only one way to collect elements of the same type. The Microsoft .NET Framework provides several classes

that also collect elements together in other specialized ways. These are the collection classes, and they live in the System.Collections namespace and sub-namespaces.

Chapter 10 Using Arrays and Collections

193

The basic collection classes accept, hold, and return their elements as objects—that is, the element type of a collection class is an object. To understand the implications of this, it is helpful to contrast an array of int variables (int is a value type) with an array of objects (object

is a reference type). Because int is a value type, an array of int variables holds its int values directly, as shown in the following graphic:

Now consider the effect when the array is an array of objects. You can still add integer values to this array. (In fact, you can add values of any type to it.) When you add an integer value, it is automatically boxed, and the array element (an object reference) refers to the boxed copy of the integer value. (For a refresher on boxing, refer to Chapter 8.) This is illustrated in the following graphic:

The element type of all the collection classes shown in this chapter is an object. This means that when you insert a value into a collection, it is always boxed, and when you remove a value from a collection, you must unbox it by using a cast. The following sections provide a very quick overview of four of the most useful collection classes. Refer to the Microsoft .NET Framework Class Library documentation for more details on each class.

Note There are collection classes that don’t always use object as their element type and that can hold value types as well as references, but you need to know a bit more about C# before we can talk about them. You will meet these collection classes in Chapter 18, “Introducing Generics.”

194 Part II Understanding the C# Language

The ArrayList Collection Class

ArrayList is a useful class for shuffling elements around in an array. There are certain occasions when an ordinary array can be too restrictive:

If you want to resize an array, you have to create a new array, copy the elements (leaving out some if the new array is smaller), and then update any references to the original array so that they refer to the new array.

If you want to remove an element from an array, you have to move all the trailing elements up by one place. Even this doesn’t quite work, because you end up with two copies of the last element.

If you want to insert an element into an array, you have to move elements down by one place to make a free slot. However, you lose the last element of the array!

Here’s how you can overcome these restrictions using the ArrayList class:

You can remove an element from an ArrayList by using its Remove method. The ArrayList automatically reorders its elements.

You can add an element to the end of an ArrayList by using its Add method. You supply the element to be added. The ArrayList resizes itself if necessary.

You can insert an element into the middle of an ArrayList by using its Insert method. Again, the ArrayList resizes itself if necessary.

You can reference an existing element in an ArrayList object by using ordinary array notation, with square brackets and the index of the element.

Note As with arrays, if you use foreach to iterate through an ArrayList, you cannot use the iteration variable to modify the contents of the ArrayList. Additionally, you cannot call the Remove, Add, or Insert method in a foreach loop that iterates through an ArrayList.

Here’s an example that shows how you can create, manipulate, and iterate through the contents of an ArrayList:

using System;

using System.Collections;

...

ArrayList numbers = new ArrayList();

...

// fill the ArrayList

foreach (int number in new int[12]{10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1})

{

numbers.Add(number);

}

...

// insert an element in the penultimate position in the list, and move the last item up

Chapter 10 Using Arrays and Collections

195

//(the first parameter is the position;

//the second parameter is the value being inserted) numbers.Insert(numbers.Count-1, 99);

//remove first element whose value is 7 (the 4th element, index 3) numbers.Remove(7);

//remove the element that’s now the 7th element, index 6 (10) numbers.RemoveAt(6);

...

//iterate remaining 10 elements using a for statement for (int i = 0; i < numbers.Count; i++)

{

int number = (int)numbers[i]; // notice the cast, which unboxes the value Console.WriteLine(number);

}

...

//iterate remaining 10 using a foreach statement

foreach (int number in numbers) // no cast needed

{

Console.WriteLine(number);

}

The output of this code is shown here:

10

9

8

7

6

5

4

3

2

99

1

10

9

8

7

6

5

4

3

2

99

1

Note The way you determine the number of elements for an ArrayList is different from querying the number of items in an array. When using an ArrayList, you examine the Count property, and when using an array, you examine the Length property.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]