[. Net Object-Oriented Programming Basics] (17) arrays and sets,. net Object-Oriented Programming

Source: Internet
Author: User
Tags array definition

[. Net Object-Oriented Programming Basics] (17) arrays and sets,. net Object-Oriented Programming

[. Net Object-Oriented Programming Basics] (17) arrays and sets

After learning the three main features of C # And the interfaces, abstract classes and other abstract things, I feel a little tired. The specific things are always easy to understand. Therefore, when we introduce the abstract concepts above, we always refer to specific instances for better understanding.

This section is very specific and easy to learn.

1. Array

1.1 What is an array?

An array is a data structure that contains multiple elements of the same type.

1.2 array Initialization

String [] mystringArray;

Type + box number array name

1.3 array Initialization

We knowArray is a reference type, so you need to allocate memory on the heap to it.

1. myIntArray = new int [3];

2. myIntArray = new int [] {1, 2, 3 };

3. int [] myIntArray = {1, 2, 3}; // when this method is used to initialize an array, it can only be used to declare an array of variables. It cannot be used after the array is declared.

1.4 array access

After the array is declared and initialized, you can use the indexer for access. The indexer always starts with 0, indicating the first element.

// Array call string [] stringArray = new string [] {"aa", "bb", "cc"}; Console. writeLine ("stringValue = \" {0} \ "", stringArray [0]); Console. readLine (); // The running result is: // stringValue = "aa"

1.5 array type

Arrays are divided into matrix arrays (one-dimensional arrays, two-dimensional arrays, and multi-dimensional arrays) and sawtooth arrays (arrays) based on different dimensions. The following describes their declaration methods.

// Array declaration string [] stringArray = new string [] {"aa", "bb", "cc"}; // The array accesses the Console. writeLine ("the first value of a one-dimensional array is {0}", stringArray [0]); // The running result is: the first value of a one-dimensional array is: aa // two-dimensional array declaration string [,] stringArray2 = new string [,] {"a1", "a2", "ac" },{ "b1 ", "b2", "b3" },{ "c1", "c2", "c3" }}; // access the Console using a two-dimensional array. writeLine ("the first dimension of a two-dimensional array has 1st values: {0}", stringArray2 [0, 0]); // The running result is: the first dimension 1st values of a two-dimensional array are a1 // 3D array access declaration int [,] myIntArray3 = new int [,] {}, {11, 11 }, {111,111 }}, {222,222}, {333,333}, {},{ 3, 3}, {3, 33}, {}}, {4, 4 }, {44,44 },{ 444,444 }}; // access the Console using a 3D array. writeLine ("the 2nd values of dimension 2 of 3D array are: {0}", myIntArray3 [, 1]); // The running result is: the 2nd dimension value of a 3D array is: 22 // a sawtooth array (also called an array) int [] [] myIntArray4 = new int [3] []; myIntArray4 [0] = new int [] {1, 11,111}; myIntArray4 [1] = new int [2] {2, 22 }; mySQL intarray4 [2] = new int [] {3, 33,333,333 3}; Console. writeLine ("the 3rd values of the 2nd arrays in the Sawtooth array are: {0}", myIntArray4 [2] [1]); // The running result is: the 3rd values of the 2nd arrays in the Sawtooth array are: 33Console. readLine ();

2. Set

2. 1. When is the set?

A set of things can be understood in a broad sense. The. NET set is defined:The. NET Framework provides specialized classes for data storage and retrieval. These classes are collectively referred to as collections. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interface.

The most common one is the ArrayList in the System. Collections namespace, which is an array automatically added to implement the IList interface as needed. Its default initial capacity is 0, so the index of the set starts from 0.

2. Differences between arrays and collections:

Before introducing the set, let's talk about the difference between the set and the array. Now that there is an array, why should C # Set a set?

The differences are as follows:

Array has its advantages, that is, continuous storage in the memory, convenient traversal, and easy to modify elements. The disadvantage is that you need to specify the array variable size. In addition, it is troublesome to add an element between the two elements.

The set does not need to define the size in advance, and the size can be automatically allocated as needed. You can also add or remove a range of elements as needed.

2.3 example:

The preceding animal family is used as an example to describe how to insert, add, and remove ArrayList collections.

1 /// <summary> 2 // animal class (parent class abstract class) 3 /// </summary> 4 abstract class Animal 5 {6 /// <summary> 7 /// name 8 /// description: class and subclass can access 9 /// </summary> 10 protected string name; 11 12 /// <summary> 13 /// constructor 14 /// </summary> 15 /// <param name = "name"> </param> 16 public animal (string name) 17 {18 this. name = name; 19} 20 21 private int shoutNum = 3; 22 public int ShoutNum 23 {24 get {return shoutNum;} 25 Set {shoutNum = value;} 26} 27 28 // <summary> 29 // name (Virtual attribute) 30 /// </summary> 31 public virtual string MyName 32 {33 get {return this. name;} 34} 35 36 // <summary> 37 // call, this method removes the virtual method, write the loop here 38 // </summary> 39 public void Shout () 40 {41 string result = ""; 42 for (int I = 0; I <ShoutNum; I ++) 43 result + = getShoutSound () + "! "; 44 45 Console. writeLine (MyName); 46 Console. writeLine (result); 47} 48 49 // <summary> 50 // create a call imaginary method, subclass rewrite 51 // </summary> 52 // <returns> </returns> 53 public virtual string getShoutSound () 54 {55 return ""; 56} 57} 58 // <summary> 59 // Dog (subclass) 60 // </summary> 61 class Dog: Animal 62 {63 string myName; 64 public Dog (string name) 65: base (name) 66 {67 myName = name; 68} 69 // <Summary> 70 // name (override parent class attributes) 71 /// </summary> 72 public override string MyName 73 {74 get {return "I am: dog, my name is: "+ this. name;} 75} 76 // <summary> 77 // call (override parent class method) 78 // </summary> 79 public override string getShoutSound () 80 {81 return "Wang! "; 82} 83} 84 85 // <summary> 86 // Cat (subclass) 87 // </summary> 88 class Cat: animal 89 {90 string myName; 91 public Cat (string name) 92: base (name) 93 {94 myName = name; 95} 96 // <summary> 97 // name (override the parent class attribute) 98 // </summary> 99 public override string MyName100 {101 get {return "I am: cat, my name is:" + this. name;} 102} 103 // <summary> 104 // call (override parent class method) 105 // </summary> 106 public override string getS HoutSound () 107 {108 return "Meow! "; 109} 110} 111 112 // <summary> 113 // goat (subclass) 114 // </summary> 115 class Sheep: Animal116 {117 string myName; 118 public Sheep (string name) 119: base (name) 120 {121 myName = name; 122} 123 // <summary> 124 // name (override parent class attributes) 125 /// </summary> 126 public override string MyName127 {128 get {return "I am: Goat, my name is:" + this. name;} 129} 130 // <summary> 131 // call (override parent class method) 132 // </summary> 133 public override string GetShoutSound () 134 {135 return! "; 136} 137}

Examples of adding, adding, and removing call and return results are as follows:

1 // IList add and insert element 2 IList animalList = new ArrayList (); 3 Cat huaHua = new Cat ("Hua"); 4 animalList. insert (0, new Dog ("wangcai"); // Insert inserts the element 5 animalList at the specified index. add (new Cat ("raccoon"); // Add inserts element 6 animalList at the end of the set. insert (animalList. count, new Sheep ("slow Goat"); 7 animalList. add (huaHua); 8 // after adding four elements, the returned results are as follows 9 Console. writeLine ("returned results after four elements are added:"); 10 foreach (Animal animal in animalList) 11 {12 animal. shout (); 13} 14 15 // remove element 16 // wangcai and Abat quit queue 17 animalList. removeAt (0); 18 animalList. removeAt (0); // note that after an element is removed, the following elements are ranked first. The second element cannot be animalList. removeAt (1); 19 animalList. remove (huaHua); // Remove refers to removing the specified element. Note that animalList cannot be removed here. remove (new Cat ("Huahua"); this write cannot be found, because new is another instance (another Cat with the same name) 20 21 // The result returned after the element is removed is as follows: 22 Console. writeLine ("returned results after removal:"); 23 foreach (Animal animal in animalList) 24 {25 animal. shout (); 26} 27 Console. readLine ();

Returned results:

2.4 disadvantages of ArrayList

The Set ArrayList has many advantages over arrays, but it also has many disadvantages.

A. ArrayList is not of type security.

ArrayList accepts all types, but actually accepts an object type.

For example:

ArrayList ar = new ArrayList();ar.Add(111);ar.Add("bbb");

When we use foreach traversal, foreach (int array in ar) {} reports an error in the degree of "bbb", so we say it is a non-secure type.

B. Large resource consumption by traversing the ArrayList

Therefore, the type is not safe. When we use ArrayList, it means to add an element and convert the value type to the Object. During traversal, the Object needs to be converted into a value type.

YesBoxing refers to converting the value type to the reference type) and unboxing refers to converting the reference type to the value type)

Because the box is packed frequently and requires a lot of computing, the overhead is very high. This is not as convenient as array. We can only say that each has its own advantages and disadvantages. Don't worry about it. the. net designers have solved the above concerns for us in Versions later than 2.0, that is, the generic model we will talk about in the next section.

3. Key points:

A. An array is A data structure that contains multiple elements of the same type.

B. set is a special class that provides data storage and retrieval in. net.

C. ArrayList is an array automatically added to implement the IList interface based on demand allocation.

D. The set and array have their own advantages and disadvantages. The array definition requires a pre-specified size. Although the set does not need to be specified in advance, the type security and resource consumption are too large.

Using Generics can solve the above problems.

========================================================== ========================================================== ====================

Returned directory

<If it is helpful to you, remember to click on the recommendations. If you do not understand the content or do not write it correctly, please contact us more>
 

========================================================== ========================================================== ====================

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.