Collection List区别

Collection是无序的,比如一大群人在广场上,你不可能说某某人是第一个,某某人是第二个

List是有序的,比如一群人从高到矮排了队,你就能说这人是第一个,这人是最后一个

因此Collection是没有index索引,没有InsertAt等方法的

Collection接口中各元素对象之间没有指定的顺序,允许有重复元素和多个null元素对象,即:类中元素无法实现排序
List接口中各元素对象之间 有 指定的顺序,允许有重复元素和多个null元素对象,即:类中元素 可以 实现排序 
搜到的,希望有帮助

在C# .net 2.0 库中,集合类就是在System、System.Collections、System.Collections.Generic和 System.Collections.ObjectModel命名空间下的类,包括Collection, KeyedCollection, ReadOnlyCollection, List, Array,Stack, Queue和ArrayList。

下面是Collection<T>, List<T>和ArrayList三个类的区别

1. List是用来在高性能环境下的类,Collection是为了扩展

使用Collection,开发人员可以重写ClearItems, InsertItem, RemoveItem 和SetItem, 因为它们是protected virtual类型的,而List<T>却没有这些扩展。

2. 实现的接口不一样

Collection<T>实现IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable

List<T>实现IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable

ArrayList实现IList, ICollection, IEnumerable, ICloneable

IList<T>,ICollection<T>, IEnumerable<T>和IList, ICollection, IEnumerable是完全不同的,前者用于范型,

view plain  
public interface IList<T> : ICollection<T>, IEnumerable<T>IEnumerable    
{    
    T Item;    
    abstract int IndexOf(T item);    
    abstract void Insert(int index, T item);    
    abstract void RemoveAt(int index);    
}    
public interface IList : ICollectionIEnumerable    
{    
    bool IsFixedSize;    
    bool IsReadOnly;    
    object Item;    
    abstract int Add(object value);    
    abstract void Clear();    
    abstract bool Contains(object value);    
    abstract int IndexOf(object value);    
    abstract void Insert(int index, object value);    
    abstract void Remove(object value);    
    abstract void RemoveAt(int index);    
}    

另一方面,Collection<T>和List<T>也实现了IList, ICollectionIEnumerable,说明这两个类比ArrayList提供了更多的方法。

3. 范型与非范型的区别

ArrayList是非范型类,如此,这个集合可以包含不同类型成员,我们可以看到,Add方法是Add(Object obj),所以这是一个对象杂陈的类。使用这个类进行操作时,IndexOf,Remove等都要使用类的Equals和HashCode,所以如果是自 己实现的类,一定要判断是否同一类型。

比如这个类是 TestType

view plain  
public override bool Equals(Object obj)    
{    
    TestType tType = obj as TestType;    
    if (tType == null)    
    {    
        return false;    
    }    
    //其它业务代码    
    ...    
}    

  

总结:

如果有扩展要求,可以考虑使用Collection<T>,如果有性能要求,考虑用List<T>,如果想存放不同类型的对象,使用ArrayList。

原文地址:https://www.cnblogs.com/kuangwong/p/8358143.html