Csharp/C Sharp/Collections Data Structure/ArrayList — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Содержание
- 1 Add array to ArrayList
- 2 Add items to ArrayList and use foreach loop to check
- 3 ArrayList Demo: hold class
- 4 Binary Search an ArrayList
- 5 Check InvalidCastException when using foreach loop with ArrayList
- 6 Checks time needed for list operations using an ArrayList implementation
- 7 Clone an ArrayList
- 8 Convert an ArrayList into an array
- 9 CopyTo, ToArray(), ToArray(typeof(String))
- 10 Demonstrate ArrayList
- 11 illustrates the use of an ArrayList that contains objects of the Car class
- 12 illustrates the use of ArrayList properties and methods
- 13 illustrates the use of ArrayLists 2
- 14 Inserting into an ArrayList by index
- 15 Remove range from ArrayList
- 16 Sort and search an ArrayList
- 17 Using foreach to loop through ArrayList and use Indexer of ArrayList
Add array to ArrayList
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("S");
baseballTeams.Add("r");
baseballTeams.Add("F");
string[] myStringArray = new string[2];
myStringArray[0] = "G";
myStringArray[1] = "L";
baseballTeams.AddRange(myStringArray);
foreach (string item in baseballTeams) {
Console.Write(item + "\n");
}
}
}
Add items to ArrayList and use foreach loop to check
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("s");
baseballTeams.Add("r");
baseballTeams.Add("F");
foreach (string item in baseballTeams) {
Console.Write(item + "\n");
}
}
}
ArrayList Demo: hold class
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
using System.Collections;
namespace ArrayListDemo
{
// a class to hold in the array list
class Employee
{
private int empID;
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
return empID.ToString();
}
public int EmpID
{
get { return empID; }
set { empID = value; }
}
}
public class ArrayListDemoTester
{
public void Run()
{
ArrayList empArray = new ArrayList();
ArrayList intArray = new ArrayList();
// populate the arraylists
for (int i = 0;i<5;i++)
{
empArray.Add(new Employee(i+100));
intArray.Add(i*5);
}
// print each member of the array
foreach (int i in intArray)
{
Console.Write("{0} ", i.ToString());
}
Console.WriteLine("\n");
// print each employee
foreach(Employee e in empArray)
{
Console.Write("{0} ", e.ToString());
}
Console.WriteLine("\n");
Console.WriteLine("empArray.Capacity: {0}",
empArray.Capacity);
}
[STAThread]
static void Main()
{
ArrayListDemoTester t = new ArrayListDemoTester();
t.Run();
}
}
}
Binary Search an ArrayList
using System;
using System.Collections;
class Album : IComparable, ICloneable {
private string _Title;
private string _Artist;
public Album(string artist, string title) {
_Artist = artist;
_Title = title;
}
public string Title {
get {
return _Title;
}
set {
_Title = value;
}
}
public string Artist {
get {
return _Artist;
}
set {
_Artist = value;
}
}
public override string ToString() {
return _Artist + ",\t" + _Title;
}
public int CompareTo(object o) {
Album other = o as Album;
if (other == null)
throw new ArgumentException();
if (_Artist != other._Artist)
return _Artist.rupareTo(other._Artist);
else
return _Title.rupareTo(other._Title);
}
public object Clone() {
return new Album(_Artist, _Title);
}
}
class TitleComparer : IComparer {
public int Compare(object l, object r) {
Album left = l as Album;
Album right = r as Album;
if ((left == null) || (right == null))
throw new ArgumentException();
if (left.Title != right.Title)
return left.Title.rupareTo(right.Title);
else
return left.Artist.rupareTo(right.Artist);
}
}
class Class1 {
static void Main(string[] args) {
ArrayList arr = new ArrayList();
arr.Add(new Album("G", "A"));
arr.Add(new Album("B", "G"));
arr.Add(new Album("S", "A"));
arr.Sort();
try {
foreach (Album a in arr) {
Console.WriteLine(a);
}
} catch (System.InvalidCastException e) {
}
arr.Sort(new TitleComparer());
foreach (Album a in arr) {
Console.WriteLine(a);
}
Album l = new Album("L", "G");
arr.Sort();
int index = arr.BinarySearch(l);
Console.WriteLine(index.ToString());
arr.Sort(new TitleComparer());
index = arr.BinarySearch(l, new TitleComparer());
Console.WriteLine(index.ToString());
}
}
Check InvalidCastException when using foreach loop with ArrayList
using System;
using System.Collections;
class Album : IComparable, ICloneable {
private string _Title;
private string _Artist;
public Album(string artist, string title) {
_Artist = artist;
_Title = title;
}
public string Title {
get {
return _Title;
}
set {
_Title = value;
}
}
public string Artist {
get {
return _Artist;
}
set {
_Artist = value;
}
}
public override string ToString() {
return _Artist + ",\t" + _Title;
}
public int CompareTo(object o) {
Album other = o as Album;
if (other == null)
throw new ArgumentException();
if (_Artist != other._Artist)
return _Artist.rupareTo(other._Artist);
else
return _Title.rupareTo(other._Title);
}
public object Clone() {
return new Album(_Artist, _Title);
}
}
public class foo {
public foo() {
myString = "Test";
}
private string myString;
}
class MainClass {
static void Main(string[] args) {
ArrayList arr = new ArrayList();
arr.Add(new Album("G", "A"));
arr.Add(new Album("B", "G"));
arr.Add(new Album("S", "A"));
arr.Sort();
arr.Insert(0, new foo());
try {
foreach (Album a in arr) {
Console.WriteLine(a);
}
} catch (System.InvalidCastException e) {
}
}
}
Checks time needed for list operations using an ArrayList implementation
using System;
using System.Drawing;
using System.Collections;
public class ArrayListTiming {
public static void Main() {
ArrayList arrayImp = new ArrayList();
Point p = new Point(34, 156);
int time1, time2;
Object o;
time1 = Environment.TickCount;
for(int i = 0; i < 100000; i++)
arrayImp.Add(p);
time2 = Environment.TickCount;
Console.WriteLine("Time for 100,000 adds: " + (time2 - time1));
time1 = Environment.TickCount;
for(int i = 0; i < 1000; i++)
arrayImp.Insert(50, p);
time2 = Environment.TickCount;
Console.WriteLine("Time for 1,000 adds at position 50: " + (time2 - time1));
time1 = Environment.TickCount;
for(int i = 0; i < 10000000; i++)
o = arrayImp[50];
time2 = Environment.TickCount;
Console.WriteLine ("Time for 10,000,000 gets at position 50: " + (time2 - time1));
}
}
Clone an ArrayList
using System;
using System.Collections;
public class Starter {
public static void Main(string[] argv) {
ArrayList al1 = new ArrayList();
foreach (string arg in argv) {
al1.Add(int.Parse(arg));
}
al1.Sort();
ArrayList al2 = (ArrayList)al1.Clone();
for (int count = 0; count < al2.Count; ++count) {
al2[count] = ((int)al2[count]) * 2;
}
foreach (int number in al2) {
Console.WriteLine(number);
}
}
}
Convert an ArrayList into an array
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Convert an ArrayList into an array.
using System;
using System.Collections;
public class ArrayListToArray {
public static void Main() {
ArrayList al = new ArrayList();
// Add elements to the array list.
al.Add(1);
al.Add(2);
al.Add(3);
al.Add(4);
Console.Write("Contents: ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine();
// Get the array.
int[] ia = (int[]) al.ToArray(typeof(int));
int sum = 0;
// sum the array
for(int i=0; i<ia.Length; i++)
sum += ia[i];
Console.WriteLine("Sum is: " + sum);
}
}
CopyTo, ToArray(), ToArray(typeof(String))
using System;
using System.Collections;
class MainClass
{
public static void Main()
{
ArrayList list = new ArrayList(5);
list.Add("B");
list.Add("G");
list.Add("J");
list.Add("S");
list.Add("M");
string[] array1 = new string[list.Count];
list.CopyTo(array1, 0);
object[] array2 = list.ToArray();
string[] array3 = (string[])list.ToArray(typeof(String));
foreach (string s in array1)
{
Console.WriteLine(s);
}
foreach (string s in array2)
{
Console.WriteLine(s);
}
foreach (string s in array3)
{
Console.WriteLine(s);
}
}
}
Demonstrate ArrayList
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate ArrayList.
using System;
using System.Collections;
public class ArrayListDemo {
public static void Main() {
// create an array list
ArrayList al = new ArrayList();
Console.WriteLine("Initial capacity: " +
al.Capacity);
Console.WriteLine("Initial number of elements: " +
al.Count);
Console.WriteLine();
Console.WriteLine("Adding 6 elements");
// Add elements to the array list
al.Add("C");
al.Add("A");
al.Add("E");
al.Add("B");
al.Add("D");
al.Add("F");
Console.WriteLine("Current capacity: " +
al.Capacity);
Console.WriteLine("Number of elements: " +
al.Count);
// Display the array list using array indexing.
Console.Write("Current contents: ");
for(int i=0; i < al.Count; i++)
Console.Write(al[i] + " ");
Console.WriteLine("\n");
Console.WriteLine("Removing 2 elements");
// Remove elements from the array list.
al.Remove("F");
al.Remove("A");
Console.WriteLine("Current capacity: " +
al.Capacity);
Console.WriteLine("Number of elements: " +
al.Count);
// Use foreach loop to display the list.
Console.Write("Contents: ");
foreach(char c in al)
Console.Write(c + " ");
Console.WriteLine("\n");
Console.WriteLine("Adding 20 more elements");
// Add enough elements to force al to grow.
for(int i=0; i < 20; i++)
al.Add((char)("a" + i));
Console.WriteLine("Current capacity: " +
al.Capacity);
Console.WriteLine("Number of elements after adding 20: " +
al.Count);
Console.Write("Contents: ");
foreach(char c in al)
Console.Write(c + " ");
Console.WriteLine("\n");
// Change contents using array indexing.
Console.WriteLine("Change first three elements");
al[0] = "X";
al[1] = "Y";
al[2] = "Z";
Console.Write("Contents: ");
foreach(char c in al)
Console.Write(c + " ");
Console.WriteLine();
}
}
illustrates the use of an ArrayList that contains objects of the Car class
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example11_3.cs illustrates the use of an ArrayList that contains
objects of the Car class
*/
using System;
using System.Collections;
// declare the Car class
class Car : IComparable
{
// declare the fields
public string model;
public int yearBuilt;
// define the constructor
public Car(string model, int yearBuilt)
{
this.model = model;
this.yearBuilt = yearBuilt;
}
// override the ToString() method
public override string ToString()
{
return "model is " + model + ", yearBuilt is " + yearBuilt;
}
// implement the Compare() method of IComparer
public int Compare(object lhs, object rhs)
{
Car lhsCar = (Car) lhs;
Car rhsCar = (Car) rhs;
if (lhsCar.yearBuilt < rhsCar.yearBuilt)
{
return -1;
}
else if (lhsCar.yearBuilt > rhsCar.yearBuilt)
{
return 1;
}
else
{
return 0;
}
}
// implement the CompareTo() method of IComparable
public int CompareTo(object rhs)
{
return Compare(this, rhs);
}
// alternative CompareTo() method that simply calls the
// CompareTo() method that comes with the int type
// (currently commented out)
/* public int CompareTo(object rhs)
{
Car rhsCar = (Car) rhs;
return this.yearBuilt.rupareTo(rhsCar.yearBuilt);
}*/
}
public class Example11_3
{
// the DisplayArrayList() method displays the elements in the
// supplied ArrayList
public static void DisplayArrayList(
string arrayListName, ArrayList myArrayList
)
{
for (int counter = 0; counter < myArrayList.Count; counter++)
{
Console.WriteLine(arrayListName + "[" + counter + "] = " +
myArrayList[counter]);
}
}
public static void Main()
{
// create an ArrayList object
ArrayList myArrayList = new ArrayList();
// add four Car objects to myArrayList using the Add() method
Console.WriteLine("Adding four Car objects to myArrayList");
Car myMR2 = new Car("MR2", 2001);
Car myBoxster = new Car("Boxster", 2001);
Car myCorvette = new Car("Corvette", 1999);
Car myThunderbird = new Car("Thunderbird", 1979);
myArrayList.Add(myMR2);
myArrayList.Add(myBoxster);
myArrayList.Add(myCorvette);
myArrayList.Add(myThunderbird);
DisplayArrayList("myArrayList", myArrayList);
// use the Contains() method to determine if myBoxster
// is in the ArrayList; if it is, then use the IndexOf()
// method to display the index
if (myArrayList.Contains(myBoxster))
{
Console.WriteLine("myArrayList does contain myBoxster");
int index = myArrayList.IndexOf(myBoxster);
Console.WriteLine("myBoxster occurs at index " + index);
}
// remove myBoxster from myArrayList
Console.WriteLine("Removing myBoxster from myArrayList");
myArrayList.Remove(myBoxster);
DisplayArrayList("myArrayList", myArrayList);
// use the Sort() method to sort myArrayList
Console.WriteLine("Using the Sort() method to sort myArrayList");
myArrayList.Sort();
DisplayArrayList("myArrayList", myArrayList);
// use the BinarySearch() method to search myArrayList for
// myCorvette
Console.WriteLine("Using the BinarySearch() method to search myArrayList\n" +
" for myCorvette");
int index2 = myArrayList.BinarySearch(myCorvette);
Console.WriteLine("Found myCorvette at index " + index2);
// use the GetRange() method to get a range of elements
// from myArrayList
Console.WriteLine("Using the GetRange() method to get two\n" +
" elements from myArrayList, starting at index 1");
ArrayList anotherArrayList = myArrayList.GetRange(1, 2);
DisplayArrayList("anotherArrayList", anotherArrayList);
// get an enumerator using the GetEnumerator() method
// and use it to read the elements in myArrayList
Console.WriteLine("Using the GetEnumerator() method to get an enumerator");
IEnumerator myEnumerator = myArrayList.GetEnumerator();
while (myEnumerator.MoveNext())
{
Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
}
// use the Reset() method and access the first row again using MoveNext()
Console.WriteLine("Using the Reset() method and accessing\n" +
" the first row again using MoveNext()");
myEnumerator.Reset();
myEnumerator.MoveNext();
Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
// Use a foreach statement to read the contents of myArrayList
Console.WriteLine("Using a foreach statement to read the contents of myArrayList");
foreach (Car myCar in myArrayList)
{
System.Console.WriteLine("myCar = " + myCar);
}
}
}
illustrates the use of ArrayList properties and methods
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example11_2.cs illustrates the use of ArrayList properties
and methods
*/
using System;
using System.Collections;
public class Example11_2
{
// the DisplayArrayList() method displays the elements in the
// ArrayList that is supplied as a parameter
public static void DisplayArrayList(
string arrayListName, ArrayList myArrayList
)
{
for (int counter = 0; counter < myArrayList.Count; counter++)
{
Console.WriteLine(arrayListName + "[" + counter + "] = " +
myArrayList[counter]);
}
}
public static void Main()
{
// create an ArrayList object
ArrayList myArrayList = new ArrayList();
// set and display the Capacity property
myArrayList.Capacity = 10;
Console.WriteLine("myArrayList.Capacity = " +
myArrayList.Capacity);
// display the IsFixedSize and IsReadOnly properties
Console.WriteLine("myArrayList.IsFixedSize = " +
myArrayList.IsFixedSize);
Console.WriteLine("myArrayList.IsReadOnly = " +
myArrayList.IsReadOnly);
// add eight string elements to myArrayList using the Add(),
// Insert(), AddRange(), and InsertRange() methods
Console.WriteLine("Adding eight string elements to myArrayList");
myArrayList.Add("This");
myArrayList.Insert(1, "is");
string[] myStringArray = {"a", "test"};
myArrayList.AddRange(myStringArray);
string[] anotherStringArray = {"Here"s", "some", "more", "text"};
myArrayList.InsertRange(myArrayList.Count, anotherStringArray);
// display the elements in myArrayList using the
// DisplayArrayList() method defined earlier
DisplayArrayList("myArrayList", myArrayList);
// use the SetRange() method to copy the elements from
// anotherStringArray to myArrayList, starting at index 0
Console.WriteLine("Using the SetRange() method to copy the\n" +
"elements from anotherStringArray to myArrayList,\n" +
"starting at index 0");
myArrayList.SetRange(0, anotherStringArray);
DisplayArrayList("myArrayList", myArrayList);
// use the Contains() method to determine if the string "text"
// is in the ArrayList; if it is, then use the IndexOf() and
// LastIndexOf() methods to display the first and last occurrence
if (myArrayList.Contains("text"))
{
int index = myArrayList.IndexOf("text");
Console.WriteLine("myArrayList does contain the word "text"");
Console.WriteLine(""text" first occurs at index " + index);
index = myArrayList.LastIndexOf("text");
Console.WriteLine(""text" last occurs at index " + index);
}
// remove element 0, first "text" element, and two
// elements starting at index 3
Console.WriteLine("Removing elements from myArrayList");
myArrayList.RemoveAt(0);
myArrayList.Remove("text");
myArrayList.RemoveRange(3, 2);
DisplayArrayList("myArrayList", myArrayList);
// use the Sort() method to sort myArrayList
Console.WriteLine("Using the Sort() method to sort myArrayList");
myArrayList.Sort();
DisplayArrayList("myArrayList", myArrayList);
// use the BinarySearch() method to search myArrayList
Console.WriteLine("Using the BinarySearch() method to search myArrayList");
int index2 = myArrayList.BinarySearch("some");
Console.WriteLine("Found "some" at index " + index2);
// use the Reverse() method to reverse myArrayList
Console.WriteLine("Using the Reverse() method");
myArrayList.Reverse();
DisplayArrayList("myArrayList", myArrayList);
// use the TrimToSize() method to reduce the capacity of
// myArrayList to the actual number of elements in myArrayList
Console.WriteLine("Using the TrimToSize() method to reduce the\n" +
"capacity of myArrayList");
myArrayList.TrimToSize();
Console.WriteLine("myArrayList.Capacity = " +
myArrayList.Capacity);
// use the GetRange() method to get a range of elements
// from myArrayList
Console.WriteLine("Using the GetRange() method to get two\n" +
"elements from myArrayList, starting at index 1");
ArrayList anotherArrayList = myArrayList.GetRange(1, 2);
DisplayArrayList("anotherArrayList", anotherArrayList);
// get an enumerator using the GetEnumerator() method
// and use it to read the elements in myArrayList
Console.WriteLine("Using the GetEnumerator() method to get an enumerator");
IEnumerator myEnumerator = myArrayList.GetEnumerator();
while (myEnumerator.MoveNext())
{
Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
}
// use the Reset() method and access the first row again using MoveNext()
Console.WriteLine("Using the Reset() method and accessing\n" +
" the first row again using MoveNext()");
myEnumerator.Reset();
myEnumerator.MoveNext();
Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current);
// Use a foreach statement to read the contents of myArrayList
Console.WriteLine("Using a foreach statement to read the contents of myArrayList");
foreach (string myString in myArrayList)
{
System.Console.WriteLine("myString = " + myString);
}
}
}
illustrates the use of ArrayLists 2
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example11_1.cs illustrates the use of ArrayLists
*/
using System;
using System.Collections;
public class Example11_1
{
// the DisplayArrayList() method displays the elements in the
// ArrayList that is supplied as a parameter
public static void DisplayArrayList(
string arrayListName, ArrayList myArrayList
)
{
for (int counter = 0; counter < myArrayList.Count; counter++)
{
Console.WriteLine(arrayListName + "[" + counter + "] = " +
myArrayList[counter]);
}
}
public static void Main()
{
// create an ArrayList object
ArrayList myArrayList = new ArrayList();
// display the Capacity property
Console.WriteLine("myArrayList.Capacity = " +
myArrayList.Capacity);
// add four strings to myArrayList using the Add() method
myArrayList.Add("This");
myArrayList.Add("is");
myArrayList.Add("a");
myArrayList.Add("test");
// display the contents of myArrayList using DisplayArrayList()
DisplayArrayList("myArrayList", myArrayList);
// create another ArrayList, passing myArrayList to the
// constructor of the new ArrayList
ArrayList anotherArrayList = new ArrayList(myArrayList);
// display the contents of anotherArrayList
DisplayArrayList("anotherArrayList", anotherArrayList);
}
}
Inserting into an ArrayList by index
using System;
using System.Collections;
class MainClass {
public static void Main() {
ArrayList al = new ArrayList(5);
// Add three elements to the end of the array
al.Add(10);
al.Add(9);
al.Add(8);
// Now, insert three elements in the front of the array
al.Insert(0, 1);
al.Insert(0, 2);
al.Insert(0, 3);
// Finally, insert into some random spots
al.Insert(2, 4);
al.Insert(4, 5);
al.Insert(6, 6);
// Enumerate the array
foreach (int i in al) {
Console.WriteLine("Entry {0}", i);
}
}
}
Remove range from ArrayList
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("s");
baseballTeams.Add("r");
baseballTeams.Add("i");
string[] myStringArray = new string[2];
myStringArray[0] = "t";
myStringArray[1] = "L";
baseballTeams.AddRange(myStringArray);
baseballTeams.RemoveRange(2, 2);
foreach (string item in baseballTeams) {
Console.Write(item + "\n");
}
Console.ReadLine();
}
}
Sort and search an ArrayList
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Sort and search an ArrayList.
using System;
using System.Collections;
public class SortSearchDemo {
public static void Main() {
// create an array list
ArrayList al = new ArrayList();
// Add elements to the array list
al.Add(55);
al.Add(43);
al.Add(-4);
al.Add(88);
al.Add(3);
al.Add(19);
Console.Write("Original contents: ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
// Sort
al.Sort();
// Use foreach loop to display the list.
Console.Write("Contents after sorting: ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
Console.WriteLine("Index of 43 is " +
al.BinarySearch(43));
}
}
Using foreach to loop through ArrayList and use Indexer of ArrayList
using System;
using System.Collections;
class CollectionsDemo {
public static void Main(String[] args) {
ArrayList PokerPlayers = new ArrayList(3);
PokerPlayers.Add("J");
PokerPlayers.Add("M");
PokerPlayers.Add("A");
PokerPlayers.Add("J");
foreach (String Player in PokerPlayers) {
Console.WriteLine(Player);
}
PokerPlayers[0] = "A";
System.Console.WriteLine(PokerPlayers[0]);
}
}