[quoted text, click to view] Lou wrote:
> I need to use collections, like class collections and just some
> generic collections and am
> not sure which is better, more efficiant etc. I noticed there are
> "Collections"
> "Dictionary"
> "Hash Table"
> and even some more.
>
> why so many collections?
> is there a reason to use one over another?
>
There are several criteria. The most important is how you will access the
data in the collection. Do you want serial access to read data (ie start at
the first item, then the second, then the third, etc) or do you want random
access (ie read item 13, read item 5, read item 22, etc)? When you write
data to the collection will you write them in the order that they will be
read (a Queue is good for this) or do you know the exact position that you
want the item in the collection (ie write item 13, then item 44 etc)?
A class that supports IEnumerable is designed to allow serial access so that
you repeatedly read a value from the collection until the end is reached. A
class that supports ICollection has the IEnumerable features as well as a
Count to determine the number of items in the collection. IDictionary means
that items can be accessed by some index object that you specify as a key
(for example the SSN is a key for a Hashtable of employee names). A class
with IList means that the collection has ransom access using the position of
the item as the index.
Do you know the size of the collection when you create it, or do you want
the collection to grow as more items are inserted? Do you want to rearrange
the order of the items after you have inserted them into the collection? Do
you want to do a search for an item with a specific value? Finally, what
type item will be in the collection - will they be the same type (eg all
strings) or will you put different types of items in the collection? If you
want to create an array of value types (eg integers or real numbers) then it
is better to use an array because the items will be 'boxed' when they are
put in the collection which means that a new object is created for each item
and this will increase your memory usage (and there are other issues with
boxing).
- Array is fixed size, allows random access and allows searches and
reordering. An array is typed.
- ArrayList is variable size, allows randowm access, searching and
reordering and is untyped. It can be used to create an array from the items
in the collection.
- Hashtable is not ordered by the order that you inserted the items, it is
variable size, allows random access. The time taken to get an item in a
Hashtable is only as good as the hash.
- SortedList contain key-value pairs, sorted according to the key, hence
inserting items takes time. Supports searches by key or value.
Richard
--
my email evpuneqt@zicf.bet is encrypted with ROT13 (
www.rot13.org)