Question

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?

Was it helpful?

Solution

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.)

OTHER TIPS

Yes, it is, unless some piece of your code changes the order by e.g. swapping.

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)

Yes. [silly answer length limit]

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top