Lists,Queues, Stacks 和 Sets
转载地址: List<T>和ArrayList
Generic的 List和非Generic的ArrayList类支持可变化大小的对象数组,它们也是最常见的集合类。ArrayList实现了IList接口,而 List<T>实现了IList<T>和IList接口(以及新增的IReadonlyList<T>)。与数组不 同,所有的接口实现都是公开的,并且Add和Remove方法也对外公开;它们会按照你的希望执行。
在List<T>和 ArrayList内部,维护了一个内部的数组对象,当这个内部数组对象的大小超过时,创建一个新的数组来替代原数组。附加元素效率很高(因为通常有一个 空闲插槽结尾),但插入的元素可能会很慢(因为有插入点之后的所有元素将位移以产生一个空闲插槽)。对于数组而言,如果集合如果是排好序的,那么执行 BinarySearch方法非常高效,但从另一个方面而言,这又不高效,因为在执行BinarySearch之前,需要检查每个元素(以排序)。
对于值类型,List<T>的比ArrayList快几倍,这是因为List<T>避免了装箱和拆箱的开销。
List<T>和ArrayList都提供了构造器方法,以接收元素集合;构造器方法遍历集合的元素到新的List<T>或ArrayList对象中。List<T>的定义大致如下:
public class List<T> : IList<T>, IReadOnlyList<T> { public List (); public List (IEnumerable<T> collection); public List (int capacity); // Add+Insert public void Add (T item); public void AddRange (IEnumerable<T> collection); public void Insert (int index, T item); public void InsertRange (int index, IEnumerable<T> collection); // Remove public bool Remove (T item); public void RemoveAt (int index); public void RemoveRange (int index, int count); public int RemoveAll (Predicate<T> match); // Indexing public T this [int index] { get; set; } public List<T> GetRange (int index, int count); public Enumerator<T> GetEnumerator(); // Exporting, copying and converting: public T[] ToArray(); public void CopyTo (T[] array); public void CopyTo (T[] array, int arrayIndex); public void CopyTo (int index, T[] array, int arrayIndex, int count); public ReadOnlyCollection<T> AsReadOnly(); public List<TOutput> ConvertAll<TOutput> (Converter <T,TOutput> converter); // Other: public void Reverse(); // Reverses order of elements in list. public int Capacity { get;set; } // Forces expansion of internal array. public void TrimExcess(); // Trims internal array back to size. public void Clear(); // Removes all elements, so Count=0. }
除了上述方法之外,List<T>还提供了与Array类一样的搜索和排序的实例方法。下面的例子演示了List的属相和方法:
static void Main(string[] args) { List<string> words = new List<string>(); words.Add("melon"); words.Add("avocado"); words.AddRange(new[] { "banana", "plum" }); words.Insert(0, "lemon"); words.InsertRange(0, new[] { "peach", "nashi" }); words.Remove("melon"); words.RemoveAt(3); words.RemoveRange(0, 2); words.RemoveAll(s => s.StartsWith("n")); Console.WriteLine(words[0]); Console.WriteLine(words[words.Count - 1]); foreach (string s in words) Console.WriteLine(s); string[] wordsArray = words.ToArray(); string[] existing = new string[1000]; words.CopyTo(0, existing, 998, 2); List<string> upperCastwords = words.ConvertAll(s => s.ToUpper()); List<int> lenghts = words.ConvertAll(s => s.Length); Console.ReadLine(); }
而非generic的ArrayList主要用于和Framework1.x的代码兼容,因为其要求一个类型转换,比如下面的代码
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68080.html