Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of an arraylist guaranteed in C#.NET?

Tags:

c#

.net

arraylist

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?

like image 823
adambox Avatar asked Nov 26 '08 15:11

adambox


People also ask

Does ArrayList guarantee order?

Yes. A List, by definition, always preserves the order of the elements. This is true not only of ArrayList, but LinkedList, Vector, and any other class that implements the java.

Is ArrayList an ordered list?

Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

Do lists maintain order?

List Vs Set. 1) List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list. Set is an unordered collection, it doesn't maintain any order.

Can you use Arraylists in C?

You can use arraylist. c and hashtable. c by placing them in your project. This library uses headers generated by makeheaders .


2 Answers

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

like image 129
Jon Skeet Avatar answered Sep 25 '22 17:09

Jon Skeet


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

like image 37
Barry Kelly Avatar answered Sep 22 '22 17:09

Barry Kelly