using System;
using System.Collections;
namespace think.collections {
public class MyArrayList : IEnumerable{
object[] elements;
int count = 0;
public int Count{ get{ return count; } }
public int Capaticy { get; set; }
public MyArrayList() {
Capaticy = 0;
}
public MyArrayList(int capacity) {
Capaticy = capacity;
elements = new object[capacity];
}
public void Add(object data) {
if (count == Capaticy) {
if (Capaticy == 0) {
elements = new object[4];
Capaticy = 4;
} else {
object[] temp = elements;
elements = new object[Capaticy*2];
for (int i = 0; i < temp.Length; i++) {
elements [i] = temp [i];
}
Capaticy *= 2;
}
}
elements [count] = data;
count++;
}
public void Sort() {
for(int j = 0; j < count; j++)
for (int i = 0; i < count -1; i++) {
if (elements [i + 1] is IComparable && elements [i] is IComparable) {
IComparable a = elements [i + 1] as IComparable;
IComparable b = elements [i] as IComparable;
if (a.CompareTo (b) > 0) {
object temp = elements [i];
elements [i] = elements [i + 1];
elements [i + 1] = temp;
}
} else {
throw new Exception ("只有实现Icomparable的元素才能排序");
}
}
}
public object this[int index]{
get {
if (index < 0 || index >= elements.Length)
throw new IndexOutOfRangeException ("下标越界");
else
return elements [index];
}
}
public IEnumerator GetEnumerator () {
//return new MyArrayListEnumerator (elements, Count);
return new ReverseEnumerator(elements,count);
}
}
public class MyArrayListEnumerator : IEnumerator{
object[] _elements;
int position = -1;
int count = 0;
public object Current {
get{
return _elements [position];
}
}
public MyArrayListEnumerator(object[] elements, int count){
this._elements = elements;
this.count = count;
}
public bool MoveNext () {
position++;
return position < count;
}
public void Reset () {
position = -1;
}
}
public class ReverseEnumerator : IEnumerator{
object[] _elements;
int position = -1;
int count = 0;
public object Current {
get{
return _elements [position];
}
}
public ReverseEnumerator(object[] elements, int count){
this._elements = elements;
this.count = count;
position = count;
}
public bool MoveNext () {
position--;
return position >= 0;
}
public void Reset () {
position = count - 1;
}
}
}
IEnumerable和IEnumerator枚举器
最新推荐文章于 2023-03-09 07:03:43 发布