Set class Array List HashTable instance operation exercises

Source: Internet
Author: User

Add, traverse, and remove Common Set Operations
Namespace System. Collections

ArrayList Variable Length array, using an array similar
Property Capacity Count
Method
Add () AddRange () Remove () RemoveAt () Clear ()
Contains () ToArray ()
A set of Hashtable key-value pairs (KeyValuePair), similar to a dictionary.

A. ArrayList operation on Value TypeCopy codeThe Code is as follows: using System;
Using System. Collections;
Namespace _ 08_ArrayList {
// ArayList operation on the Value Type
Class Program {
Static void Main (string [] args ){
// There is not much difference between ArrayList and array. The advantage is that it is not as long as the array needs to be specified. The disadvantage is that there are many errors when the data type is not limited to any type of data.
ArrayList arylist = new ArrayList ();
// Add ArrayList
Arylist. Add (1, 1000 );
// Arylist. Add ("zhangsan"); // The parameter type is object. Therefore, you can Add multiple types of parameters to be converted.
Arylist. Add (1, 3000 );
Arylist. Add (4000); // In case of boxing, convert the value type to the reference type.
Arylist. Add (1, 5000 );
Int [] arr = {1, 2, 3, 4 };
Arylist. AddRange (arr); // The AddRange parameter is an object that implements the ICollections interface. You can add an array, array, ArrayList, and other objects that implement interfaces at a time.
// Use Count = array Length for the number of elements in the Set
Console. WriteLine ("set content length" + arylist. Count );
// Capacity indicates that the Capacity of the set is variable, generally * 2 Growth
Console. WriteLine (arylist. Capacity );
// Access the first element of the Set
Int firstlist = Convert. ToInt32 (arylist [0]);
Console. WriteLine (firstlist. ToString ());
// ArrayList Traversal
Int sum2 = 0;
For (int I = 0; I <arylist. Count; I ++ ){
// Sum2 + = Convert. ToInt32 (arylist [I]); // unpack
Console. WriteLine (arylist [I]. ToString ());
}
Foreach (object item in arylist ){
Sum2 + = Convert. ToInt32 (item );
}
Console. WriteLine (sum2 );
// Remove the ArrayList, but not delete it.
Arylist. Remove (1000); // The removal content is 1000. Remove an internal object.
Arylist. RemoveAt (1); // remove the second item by index
// Note that removing the element ArrayList array will re-allocate the index. Therefore, it is best to remove the element in reverse mode.
// Directly use Clear if all elements are removed
// Arylist. Clear ();
If (arylist. Contains (3000 )){
Console. WriteLine ("included ");
}
// ArrayList has ToArray (), but it does not make much sense.
// Here the value-added type is added to the ArrayList. What about the reference type ???? Add the Student class object?
Console. Read ();
}
}
}

B. ArrayList operations on the reference typeCopy codeThe Code is as follows: using System;
Using System. Collections;
Namespace _ 09_ArrayListObject {
// ArrayList operation on the reference type
Class Student {
Public Student (string name, int age ){
This. name = name;
This. age = age;
}
Private string name;
Public string Name {
Get {
Return name;
}
Set {
Name = value;
}
}
Private int age;
Public int Age {
Get {
Return age;
}
Set {
Age = value;
}
}
}
Class Program {
Static void Main (string [] args ){
Student xyy = new Student ("", 14 );
Student fj = new Student ("Fengjie", 18 );
Student fr = new Student ("Sister Furong", 19 );
Student xl = new Student ("sharp brother", 20 );
ArrayList student = new ArrayList ();
Student. Add (xyy); // you can also use AddRange to Add
Student. Add (fj );
Student. Add (fr );
Student. Add (xl );
// Remove
// Student. Remove (fj); // The removed object is not a value.
// Student. RemoveAt (1); // index Removal
// The object cannot be removed because the object is removed by index after the removal.
// Student stu = new Student ("Fengjie", 18 );
// Student. Remove (stu );
// Console. WriteLine (student. Contains (stu); // false index retrieval because stu and fj address are different
// Traverse
For (int I = 0; I <student. Count; I ++ ){
Student s = student [I] as Student; // because the packing operation is performed before adding the student [I], the name cannot be clicked.
Console. WriteLine (s. Name );
}
ArrayList ary = new ArrayList ();
Ary. Add ("Fengjie ");
Ary. Add (" ");
// The string class is also a reference type, but it is somewhat special here
String name = "Fengjie ";
Console. WriteLine (ary. Contains (name); // string compares the content, so true is returned.
// Obtain the student object based on the student name. Although ArrayList can be implemented, it is complicated and inefficient. So next we will learn HashTable.
Console. Read ();
}
}
}

C. HashTableCopy codeThe Code is as follows: using System;
Using System. Collections;
Namespace _ 10_HashTable {
Class Student {
Public Student (string name, int age ){
This. name = name;
This. age = age;
}
Private string name;
Public string Name {
Get {
Return name;
}
Set {
Name = value;
}
}
Private int age;
Public int Age {
Get {
Return age;
}
Set {
Age = value;
}
}
}
Class Program {
Static void Main (string [] args ){
// The Student class is still used for implementation.
// Hashtable key-value pairs form the key value, which is equivalent to a dictionary that can quickly locate an object based on the student's name
Student xyy = new Student ("", 14 );
Student fj = new Student ("Fengjie", 18 );
Student fr = new Student ("Sister Furong", 19 );
Student xl = new Student ("sharp brother", 20 );
Hashtable student = new Hashtable ();
Student. Add ("", xyy );
Student. Add ("Fengjie", fj );
Student. Add ("Sister Furong", fr );
Student. Add ("sharp brother", xl );
// Student. Add ("sharp brother", xl); // The keyword key in the error dictionary cannot be repeated, so you cannot Add a sharp brother.
// Remove RemoveAt () because there is no index ()
Student. Remove (""); // Remove it based on the key
Student. Clear ();
Student. ContainsKey ("Fengjie"); // you can check whether this key exists.
// Because the dictionary does not have an index, you cannot use the for traversal. You can only use the foreach
// Key-based traversal is often used
Foreach (object key in student. Keys ){
Student stu = student [key] as Student;
Console. WriteLine (key );
Console. WriteLine (stu. Age );
}
// Traverse by value
Foreach (object value in student. Values ){
Student stu = value as Student;
If (stu! = Null ){
Console. WriteLine (stu. Age );
}
}
// If you do not press the key or the value to traverse the dictionary, the dictionary's key-value pair will be traversed.
Foreach (DictionaryEntry de in student ){
Console. WriteLine (de. Key );
Student s = de. Value as Student; // The conversion is required because the object type is obtained.
Console. WriteLine (s. Age );
}
Student s2 = student [""] as Student; // locate the object by name and obtain other attributes.
If (s2! = Null ){
Console. WriteLine (s2.Age );
}
Console. Read ();
}
}
}

D. ExerciseCopy codeThe Code is as follows: using System;
Using System. Collections;
Namespace _ 11_ArrayList exercise {
Class Program {
// It is the most important to start writing code after understanding the question.
Static void Main (string [] args ){
// Two sets: {"a", "B", "c", "d", "e"} and {"d", "e", "f ", "g", "h"}, remove duplicate items from the two sets and combine them into one
ArrayList ary1 = new ArrayList {"a", "B", "c", "d", "e "};
ArrayList ary2 = new ArrayList {"d", "e", "f", "g", "h "};
// Traverse two sets
For (int I = 0; I <ary2.Count; I ++) {// compare the elements of ary2 with that of ary1 in a loop traversal. If the values are the same one by one, do not add them. Otherwise, append them to ary1.
If (! Ary1.Contains (ary2 [I]) {// There Is A Contains method. If you do not know how complicated it is
Ary1.Add (ary2 [I]);
}
}
Foreach (object item in ary1 ){
Console. Write (item );
}
// Randomly generate 10 numbers between 1 and put them in the ArrayList. The 10 numbers must be unique and even.
ArrayList arylist = new ArrayList ();
// Int numCount = 0;
While (true ){
Random ran = new Random ();
Int num = ran. Next (1,100 );
If (num % 2 = 0 &&! Arylist. Contains (num) {// Add! Arylist. Contains (num) solves the following problems:
Arylist. Add (num); // Why is the first value that meets the condition displayed when running the command directly while the result of one-step debugging displayed correctly ???
}
If (arylist. Count = 10 ){
Break;
}
}
Foreach (object item in arylist ){
Console. WriteLine (item );
}
// A string is a series of integers separated by spaces. Write a program to rearrange the integers as follows: the odd numbers are displayed on the left and the even numbers are displayed on the right. For example, '2 7 8 3 22 9 'is displayed as '7 3 9 2 8 22
String str = "2 7 8 3 22 9 ";
ArrayList ary3 = new ArrayList ();
ArrayList ary4 = new ArrayList ();
String [] s = str. Split ('');
Foreach (var item in s ){
If (Convert. ToInt32 (item) % 2 = 0 ){
Ary4.Add (item );
} Else {
Ary3.Add (item );
}
}
Ary3.AddRange (ary4); // because the ary1 type is object, you cannot use the join method of the string class to implement character concatenation. You can process a generic set after learning it.
String newstr = ary3 [0]. ToString (); // remove spaces in a simple way
For (int I = 1; I <ary3.Count; I ++ ){
Newstr + = "" + ary3 [I];
}
Console. WriteLine ("original string: {0}, filtered string {1}", str, newstr + "test ");
Console. Read ();
}
}
}

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.