If I'm using an ArrayList in C#.NET, is the order guaranteed to stay the same as the order I add items to it?
+5
A:
Yes, it is, unless some piece of your code changes the order by e.g. swapping.
Barry Kelly
2008-11-26 15:29:40
+14
A:
Yes, elements are always added to the end (unless you specify otherwise, e.g. with a call to Insert). In other words, if you do:
int size = list.Count;
int index = list.Add(element);
Assert.AreEqual(size, index); // Element is always added at the end
Assert.AreEqual(element, list[index]); // Returned index is position in list
The position will change if you remove any earlier elements or insert new elements ahead of it, of course.
Is there any good reason for you to use ArrayList
rather than List<T>
by the way? Non-generic collections are so 2003...
(The order is stable in List<T>
as well, by the way.)
Jon Skeet
2008-11-26 15:29:47
"Non-generic collections are so 2003..." - LOL, nice one Jon, that's going up as my quote of the week :)
DoctaJonez
2008-11-26 16:57:55
A:
When you add an item to a ArrayList the item will always stay at that index. Unless of course if you change it.
(the framework might rearrange the memory but your index will always stay the same)
Y Low
2008-11-26 15:30:47
+3
A:
Yes it is. Since it's stored as an array.
Other properties are
- Guaranteed order
- Random access. You can access any element by index in O(1)
- Slow insert and delete in the beginning and middle.
- Unsorted. (Sorting should take O(n log n) using quicksort or similar)
Mats Fredriksson
2008-11-26 15:32:16